新知识点
1.撤销
textArea添加一个实现监听接口的类(添加了之后可以一直监视着添加的删除的情况,以便来撤销
textArea.getDocument().addUndoableEditListener( new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { undoManager.addEdit(e.getEdit()); updateButtons(); } });
再弄一个管理监听的类,可以撤销和恢复
UndoManager undoManager = new UndoManager();
undoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { undoManager.undo(); } catch (CannotRedoException cre) { cre.printStackTrace(); } updateButtons(); } }); redoButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { undoManager.redo(); } catch (CannotRedoException cre) { cre.printStackTrace(); } updateButtons(); } });
2删除选中的文本
int start = text.getSelectionStart(); int end =text.getSelectionEnd(); text.replaceRange("", start, end); // 删除被选取的文本。
3设置时间格式
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 String s=df.format(new Date());
4激活自动换行
text.setLineWrap(true);//激活自动换行功能 text.setWrapStyleWord(true);//激活断行不断字功能(有单词会跳
5设置字体
font.setAccelerator(KeyStroke.getKeyStroke('a'));//点开菜单单键 font.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK));//使用组合键 font.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0));//全局不用组合键
6打包后文件路径有错
因为打包后文件路径变了,要用URL来获得资源,由于,getClass().getResource是Object类的,可以用this调用
URL url = this.getClass().getResource("/2.png"); ImageIcon addIcon = new ImageIcon(url); about.setIcon(addIcon);
bug:
1选中文本换颜色不能实现
全部代码
package testWin; import java.awt.event.*; import java.awt.*; import javax.swing.*; import javax.swing.event.*; public class FontDialog extends JDialog implements ListSelectionListener,ActionListener { FontFamilyNames fontFamilyNames; int fontSize=12; int fontStyle=0; String fontName="宋体"; JList fontNameList,fontSizeList,fontStyleList; Font font; JButton yes,cancel; static int YES=1,NO=0; int state=-1; FontDialog(JFrame f) { super(f); setTitle("字体对话框"); //font=new Font("宋体",Font.PLAIN,12); fontFamilyNames=new FontFamilyNames(); setModal(true);//当前对话框调用setModal(boolean b)设置为有模式 //字体列表框: String[] name=fontFamilyNames.getFontName(); fontNameList=new JList(); fontNameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fontNameList.setListData(name); fontNameList.setVisibleRowCount(8); //设置列表框第一条被选中 fontNameList.setSelectedIndex(0); //添加滚动条 JScrollPane p1=new JScrollPane(fontNameList); fontNameList.addListSelectionListener(this); //字形列表框: String[] style={"常规 ","粗体","斜体","粗斜体"}; fontStyleList=new JList(); fontStyleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fontStyleList.setListData(style); fontStyleList.setVisibleRowCount(8); fontStyleList.setSelectedIndex(0); JScrollPane p2=new JScrollPane(fontStyleList); fontStyleList.addListSelectionListener(this); //大小列表框: String[] size={"8 ","10","12","14","16","18","20","22","24","26","28","30","32"}; fontSizeList=new JList(); fontSizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fontSizeList.setListData(size); fontSizeList.setVisibleRowCount(8); fontSizeList.setSelectedIndex(0); JScrollPane p3=new JScrollPane(fontSizeList); fontSizeList.addListSelectionListener(this); JPanel listPanel=new JPanel(); listPanel.add(p1); listPanel.add(p2); listPanel.add(p3); add(listPanel,BorderLayout.NORTH); yes=new JButton("确定"); cancel=new JButton("取消"); yes.addActionListener(this); cancel.addActionListener(this); JPanel pSouth=new JPanel(); pSouth.add(yes); pSouth.add(cancel); add(pSouth,BorderLayout.SOUTH); setBounds(250,150,400,250); setDefaultCloseOperation(DISPOSE_ON_CLOSE); validate(); } public void valueChanged(ListSelectionEvent e){ if(e.getSource()==fontNameList) { fontName=(String)fontNameList.getSelectedValue(); } else if(e.getSource()==fontStyleList) { fontStyle=fontStyleList.getSelectedIndex(); } else if(e.getSource()==fontSizeList) { String s=(String)fontSizeList.getSelectedValue(); fontSize=Integer.parseInt(s.trim()); } font=new Font(fontName,fontStyle,fontSize); validate(); } public void actionPerformed(ActionEvent e) { if(e.getSource()==yes) { state=YES; setVisible(false); //对话框设置为不可见 } else if(e.getSource()==cancel) { state=NO; setVisible(false); } } public int getState() { return state; } public Font getFont() { return font; } }
package testWin; import java.awt.GraphicsEnvironment; public class FontFamilyNames { String allFontNames[]; public String [] getFontName() { GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment(); allFontNames=ge.getAvailableFontFamilyNames(); return allFontNames; } }
package testWin; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.undo.UndoManager; public class Polish implements ActionListener{ JFileChooser file1=new JFileChooser(); FileNameExtensionFilter filter=new FileNameExtensionFilter("txt文件","txt");//文件名过滤 private JTextArea text; private int huanhang=0;//换行参数 UndoManager undoManager; private JFrame frame; void setFrame(JFrame a){ frame=a; } void setText(JTextArea a){ text=a; } void setUnodManager(UndoManager a){ undoManager=a; } @Override public void actionPerformed(ActionEvent e) { // TODO 自动生成的方法存根 if(e.getActionCommand().equals("撤销")){ undoManager.undo(); }else if(e.getActionCommand().equals("剪贴")){ text.cut(); }else if(e.getActionCommand().equals("复制")){ text.copy(); }else if(e.getActionCommand().equals("粘贴")){ text.paste(); }else if(e.getActionCommand().equals("删除")){ int start = text.getSelectionStart(); int end =text.getSelectionEnd(); text.replaceRange("", start, end); // 删除被选取的文本。 // String s=text.getText(); 方法2 // String a=text.getSelectedText(); // text.setText(s.replace(a,"")); }else if(e.getActionCommand().equals("全选")){ text.selectAll(); }else if(e.getActionCommand().equals("时间/日期")){ Calendar calendar=Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 String s=df.format(new Date()); text.append(s); }else if(e.getActionCommand().equals("自动换行")){ if(huanhang%2==0){ text.setLineWrap(true);//激活自动换行功能 text.setWrapStyleWord(true);//激活断行不断字功能(有单词会跳 }else{ text.setLineWrap(false); text.setWrapStyleWord(false); } huanhang++; }else if(e.getActionCommand().equals("颜色")){ Color color2=new Color(120,30,0); Color color1=JColorChooser.showDialog(frame,"color",color2); text.setForeground(color1); text.setSelectedTextColor(color1); // JColorChooser jc=new JColorChooser(); // Color color3=jc.showDialog(null,"zb",color2); // text.setSelectedTextColor(color3); }else if(e.getActionCommand().equals("字体")){ FontDialog dialog1=new FontDialog(frame); dialog1.setVisible(true); Font font1=dialog1.getFont(); text.setFont(font1); }else if(e.getActionCommand().equals("关于笔记本")){ JOptionPane.showMessageDialog(frame, "2015118043,黄煜成,2016/11/17完成"); }else if(e.getActionCommand().equals("打开")){ file1.setFileFilter(filter);//过滤下 int state=file1.showOpenDialog(frame); if(state==JFileChooser.APPROVE_OPTION){ try{ File dir=file1.getSelectedFile(); FileReader fileReader=new FileReader(dir); BufferedReader in1=new BufferedReader(fileReader); text.setText(null); String s=null; for(;(s=in1.readLine())!=null;){ text.append(s+" "); } in1.close(); fileReader.close(); } catch(Exception e1){ System.out.println(e1.getMessage()); } } }else if(e.getActionCommand().equals("另存为")){ file1.setFileFilter(filter);//过滤下 int state=file1.showSaveDialog(frame);//显示出保存框 if(state==JFileChooser.APPROVE_OPTION){ try{ File dir=file1.getCurrentDirectory();//得到保存路径 String name=file1.getSelectedFile().getName();//得到选择的的名字 File file=new File(dir,name); FileWriter fileWriter=new FileWriter(file); BufferedWriter out1=new BufferedWriter(fileWriter); out1.write(text.getText()); out1.close(); fileWriter.close(); } catch(IOException e3){ System.out.println(e3.getMessage()); } } } else if(e.getActionCommand().equals("新建")){ int n = 0; if(text.getText()!="") n=JOptionPane.showConfirmDialog(frame, "是否保存"); if(n==JOptionPane.YES_OPTION){ file1.setFileFilter(filter);//过滤下 int state=file1.showSaveDialog(frame);//显示出保存框 if(state==JFileChooser.APPROVE_OPTION){ try{ File dir=file1.getCurrentDirectory();//得到保存路径 String name=file1.getSelectedFile().getName();//得到选择的的名字 File file=new File(dir,name); FileWriter fileWriter=new FileWriter(file); BufferedWriter out1=new BufferedWriter(fileWriter); out1.write(text.getText()); out1.close(); fileWriter.close(); } catch(IOException e3){ System.out.println(e3.getMessage()); } } } else if(n==JOptionPane.NO_OPTION){ text.setText(null); } }else if(e.getActionCommand().equals("退出")){ System.exit(0); }else if(e.getActionCommand().equals("保存")){ System.out.println("1111"); File file1=new File ("新建保存文件.txt"); if(!file1.exists()) try { file1.createNewFile(); } catch (IOException e1) { e1.printStackTrace(); } try{ FileWriter fileWriter=new FileWriter(file1); BufferedWriter out1=new BufferedWriter(fileWriter); out1.write(text.getText()); out1.close(); fileWriter.close(); } catch(Exception e5){ System.out.println(e5.getMessage()); } } } }
package testWin; import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Image; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.border.EmptyBorder; import javax.swing.undo.UndoManager; public class Text extends JFrame { private JPanel contentPane; JTextArea textArea = new JTextArea(); UndoManager undoManager = new UndoManager(); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Text frame = new Text(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Text() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 681, 570); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu file = new JMenu("u6587u4EF6"); menuBar.add(file); JMenuItem newFile = new JMenuItem("u65B0u5EFA"); newFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK)); file.add(newFile); JMenuItem openFile = new JMenuItem("u6253u5F00"); openFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK)); file.add(openFile); JMenuItem saveFile = new JMenuItem("u4FDDu5B58"); saveFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK)); file.add(saveFile); JMenuItem save2File = new JMenuItem("u53E6u5B58u4E3A"); save2File.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.CTRL_MASK)); file.add(save2File); JMenuItem print = new JMenuItem("u6253u5370"); print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK)); file.add(print); JMenuItem close = new JMenuItem("u9000u51FA"); close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK)); file.add(close); JMenu menu = new JMenu("u7F16u8F91"); menuBar.add(menu); JMenuItem revoke = new JMenuItem("u64A4u9500"); revoke.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK)); menu.add(revoke); JMenuItem clip = new JMenuItem("u526Au8D34"); clip.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_MASK)); menu.add(clip); JMenuItem copy = new JMenuItem("u590Du5236"); copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK)); menu.add(copy); JMenuItem paste = new JMenuItem("u7C98u8D34"); paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK)); menu.add(paste); JMenuItem delete = new JMenuItem("u5220u9664"); delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_MASK)); menu.add(delete); JMenuItem selectAll = new JMenuItem("u5168u9009"); selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK)); menu.add(selectAll); JMenuItem date = new JMenuItem("u65F6u95F4/u65E5u671F"); menu.add(date); JMenu format = new JMenu("u683Cu5F0F"); menuBar.add(format); JMenuItem autoNextLine = new JMenuItem("u81EAu52A8u6362u884C"); autoNextLine.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK)); format.add(autoNextLine); JMenuItem font = new JMenuItem("u5B57u4F53"); font.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, InputEvent.CTRL_MASK)); format.add(font); JMenuItem color = new JMenuItem("u989Cu8272"); format.add(color); JMenu help = new JMenu("u5E2Eu52A9"); menuBar.add(help); JMenuItem about = new JMenuItem("u5173u4E8Eu7B14u8BB0u672C"); about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK)); URL url = this.getClass().getResource("/2.png"); ImageIcon addIcon = new ImageIcon(url); about.setIcon(addIcon); help.add(about); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JScrollPane scrollPane = new JScrollPane(); contentPane.add(scrollPane, BorderLayout.CENTER); scrollPane.setViewportView(textArea); Polish polish1=new Polish();//锟斤拷锟斤拷锟斤拷 UndoPolish undo=new UndoPolish();//锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷 textArea.getDocument().addUndoableEditListener(undo);//锟斤拷映锟斤拷锟斤拷锟斤拷锟� undo.setUnodManager(undoManager); polish1.setText(textArea); polish1.setUnodManager(undoManager);//锟斤拷锟捷癸拷锟斤拷锟斤拷 polish1.setFrame(this); revoke.addActionListener(polish1);//锟斤拷蛹锟斤拷锟� clip.addActionListener(polish1); copy.addActionListener(polish1); paste.addActionListener(polish1); delete.addActionListener(polish1); selectAll.addActionListener(polish1); date.addActionListener(polish1); autoNextLine.addActionListener(polish1); color.addActionListener(polish1); font.addActionListener(polish1); about.addActionListener(polish1); openFile.addActionListener(polish1); save2File.addActionListener(polish1); newFile.addActionListener(polish1); close.addActionListener(polish1); saveFile.addActionListener(polish1); } public ImageIcon getMyImage(String imageName){ ClassLoader loader = getClass().getClassLoader(); java.io.InputStream is = loader.getResourceAsStream(imageName); Image img; ImageIcon ii = null; try { img = ImageIO.read(is); ii = new ImageIcon(img); return ii; } catch (IOException e) { e.printStackTrace(); } return ii; } }
package testWin; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.undo.CannotRedoException; import javax.swing.undo.UndoManager; public class UndoPolish implements UndoableEditListener{ UndoManager undoManager; void setUnodManager(UndoManager a){ undoManager=a; } @Override public void undoableEditHappened(UndoableEditEvent e) { // TODO 自动生成的方法存根 undoManager.addEdit(e.getEdit()); } }