仿照windows记事本,制作一个记事本软件,实现纯文本文件的新建、打开、保存、另存、复制、粘贴、查找、替换、关于等功能。
import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*; import javax.swing.event.*; import java.awt.datatransfer.*; public class Window extends JFrame implements ActionListener,DocumentListener{ //系统剪贴板 Toolkit toolkit=Toolkit.getDefaultToolkit(); Clipboard clipBoard=toolkit.getSystemClipboard(); //用来复制粘贴 //右键弹出菜单项 JPopupMenu popupMenu; JMenuItem popupMenu_Undo,popupMenu_Cut,popupMenu_Copy,popupMenu_Paste,popupMenu_Delete,popupMenu_SelectAll; String oldValue;//存放编辑区原来的内容,用于比较文本是否有改动 boolean isNewFile=true;//是否新文件(未保存过的) File currentFile;//当前文件名 File file = null; JMenuBar bar; JLabel label;//其他变量 JMenu files ,edit, form ,look ,help; JMenuItem news,open,save, saves, copy ,paste ,find, replace,replaceAll,cut; JTextArea editArea; Window(){ setTitle("记事本"); files = new JMenu("文件"); edit = new JMenu("编辑"); form =new JMenu("格式"); look =new JMenu("查看"); help =new JMenu("帮助"); news = new JMenuItem("新建"); open = new JMenuItem("打开"); save = new JMenuItem("保存"); saves = new JMenuItem("另存"); copy = new JMenuItem("复制"); cut = new JMenuItem("剪切"); paste = new JMenuItem("粘贴"); find = new JMenuItem("查找"); replace = new JMenuItem("替换"); // replaceAll = new JMenuItem("全部替换"); bar = new JMenuBar(); files.add(news); news.addActionListener(this);//添加监听器 files.add(saves); saves.addActionListener(this); files.add(open); open.addActionListener(this); files.add(save); save.addActionListener(this); files.add(find); find.addActionListener(this); form.add(replace); replace.addActionListener(this); // form.add(replaceAll); //replaceAll.addActionListener(this); edit.add(copy); copy.addActionListener(this); edit.add(paste); paste.addActionListener(this); files.add(cut); cut.addActionListener(this); bar.add(files); bar.add(edit); bar.add(form); bar.add(look); bar.add(help); setJMenuBar(bar); //文本区 editArea = new JTextArea(200,300); JScrollPane scroll = new JScrollPane (editArea); editArea.setWrapStyleWord(true);//设置单词在一行不足容纳时换行 editArea.setLineWrap(true);//设置文本编辑区自动换行默认为true,即会"自动换行" add(editArea); popupMenu = new JPopupMenu(); //popupMenu_Undo=new JMenuItem("撤销"); popupMenu_Cut=new JMenuItem("剪切"); popupMenu_Copy=new JMenuItem("复制"); popupMenu_Paste=new JMenuItem("粘帖"); popupMenu_Delete=new JMenuItem("删除"); popupMenu_SelectAll=new JMenuItem("全选"); //向右键菜单添加菜单项和分隔符 // popupMenu.add(popupMenu_Undo); popupMenu.addSeparator(); popupMenu.add(popupMenu_Cut); popupMenu.add(popupMenu_Copy); popupMenu.add(popupMenu_Paste); popupMenu.add(popupMenu_Delete); popupMenu.addSeparator(); popupMenu.add(popupMenu_SelectAll); //文本编辑区注册右键菜单事件 //popupMenu_Undo.addActionListener(this); popupMenu_Cut.addActionListener(this); popupMenu_Copy.addActionListener(this); popupMenu_Paste.addActionListener(this); popupMenu_Delete.addActionListener(this); popupMenu_SelectAll.addActionListener(this); //右键菜单 editArea.addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ if(e.isPopupTrigger()) //返回此鼠标事件是否为该平台的弹出菜单触发事件 {popupMenu.show(e.getComponent(),e.getX(),e.getY());}//在组件调用者的坐标空间中的位置 X、Y 显示弹出菜单 checkMenuItemEnabled();//设置剪切,复制,粘帖,删除等功能的可用性 editArea.requestFocus();//编辑区获取焦点 } public void mouseReleased(MouseEvent e){ if(e.isPopupTrigger()){//返回此鼠标事件是否为该平台的弹出菜单触发事件 popupMenu.show(e.getComponent(),e.getX(),e.getY());//在组件调用者的坐标空间中的位置 X、Y 显示弹出菜单 } checkMenuItemEnabled();//设置剪切,复制,粘帖,删除等功能的可用性 editArea.requestFocus();//编辑区获取焦点 } });//文本编辑区注册右键菜单事件结束 //添加窗口监听器 addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { editArea.requestFocus(); String currentValue=editArea.getText(); //System.out.println(oldValue); if(currentValue.equals(oldValue)==true)//判断是否为新文件 { System.exit(0); } else { exitWindowChoose(); } } }); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); setBounds(100,50,420,380); validate(); }//构造方法结束 //关闭窗口时判断新建 public void exitWindowChoose() { editArea.requestFocus(); String currentValue=editArea.getText(); if(currentValue.equals(oldValue)==true)//判断是否为新文件 { System.exit(0); } else{ int exitChoose=JOptionPane.showConfirmDialog(this,"您的文件尚未保存,是否保存?","退出提示",JOptionPane.YES_NO_CANCEL_OPTION); if(exitChoose==JOptionPane.YES_OPTION){ //boolean isSave=false; if(isNewFile){ JFileChooser fileDialog = new JFileChooser(); int state = fileDialog.showSaveDialog(this); if(state == JFileChooser.APPROVE_OPTION) { try { File dir = fileDialog.getCurrentDirectory(); String name = fileDialog.getSelectedFile().getName(); File file = new File(dir,name); FileWriter fileWriter = new FileWriter(file); BufferedWriter out = new BufferedWriter(fileWriter); out.write(editArea.getText()); out.close(); fileWriter.close(); } catch(IOException e) { } } } } } } @Override public void actionPerformed(ActionEvent e ) { if(e.getSource()==copy||e.getSource()==popupMenu_Copy) {//复制粘贴剪切 editArea.copy(); } if(e.getSource()==popupMenu_SelectAll) { editArea.select(0,editArea.getText().length()); } if(e.getSource()==cut||e.getSource()==popupMenu_Cut) { editArea.cut(); } if(e.getSource()==paste||e.getSource()==popupMenu_Paste) { editArea.paste(); } //打开或新建 if(e.getSource()==open||e.getSource()==news) { editArea.requestFocus(); String currentValue=editArea.getText(); if(currentValue.equals(oldValue)==true)//判断是否为新文件 { System.exit(0); } else{ int exitChoose=JOptionPane.showConfirmDialog(this,"您的文件尚未保存,是否保存?","退出提示",JOptionPane.YES_NO_CANCEL_OPTION); if(exitChoose==JOptionPane.YES_OPTION){ //boolean isSave=false; if(isNewFile){ JFileChooser fileDialog = new JFileChooser(); int state = fileDialog.showSaveDialog(this); if(state == JFileChooser.APPROVE_OPTION) { try { File dir = fileDialog.getCurrentDirectory(); String name = fileDialog.getSelectedFile().getName(); File file = new File(dir,name); FileWriter fileWriter = new FileWriter(file); BufferedWriter out = new BufferedWriter(fileWriter); out.write(editArea.getText()); out.close(); fileWriter.close(); } catch(IOException ex) { } }} } } } if(e.getSource()==find) { final JDialog findDialog=new JDialog(this,"查找",false);//false时允许其他窗口同时处于激活状态(即无模式) Container con=findDialog.getContentPane();//返回此对话框的contentPane对象 con.setLayout(new FlowLayout(FlowLayout.LEFT)); JLabel findContentLabel=new JLabel("查找内容:"); final JTextField findText=new JTextField(15); JButton findNextButton=new JButton("查找下一个:"); final JCheckBox matchCheckBox=new JCheckBox("区分大小写"); ButtonGroup bGroup=new ButtonGroup(); final JRadioButton upButton=new JRadioButton("向上"); final JRadioButton downButton=new JRadioButton("向下"); downButton.setSelected(true); bGroup.add(upButton); bGroup.add(downButton); /*JRadioButton此类实现一个单选按钮,并可为用户显示其状态。 与 ButtonGroup 对象配合使用创建一组按钮,一次只能选择其中的一个按钮。 (创建一个 ButtonGroup 对象并用其 add 方法将 JRadioButton 对象包含在此组中。)*/ //"查找下一个"按钮监听 findNextButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e)//适配器 { //"区分大小写(C)"的JCheckBox是否被选中 int k=0,m=0; final String str1,str2,str3,str4,strA,strB; str1=editArea.getText(); str2=findText.getText(); str3=str1.toUpperCase(); str4=str2.toUpperCase(); if(matchCheckBox.isSelected())//区分大小写 { strA=str1; strB=str2; } else//不区分大小写,此时把所选内容全部化成大写(或小写),以便于查找 { strA=str3; strB=str4; } if(upButton.isSelected()) { if(editArea.getSelectedText()==null) k=strA.lastIndexOf(strB,editArea.getCaretPosition()-1);//从零开始,光标位置减一 else k=strA.lastIndexOf(strB, editArea.getCaretPosition()-findText.getText().length()-1); if(k>-1) { editArea.setCaretPosition(k);//设置光标位置到那 editArea.select(k,k+strB.length());//将查找到的内容选择 } else { JOptionPane.showMessageDialog(null,"找不到您查找的内容!","查找",JOptionPane.INFORMATION_MESSAGE); } } else if(downButton.isSelected()) { if(editArea.getSelectedText()==null) k=strA.indexOf(strB,editArea.getCaretPosition()+1); else k=strA.indexOf(strB, editArea.getCaretPosition()-findText.getText().length()+1); if(k>-1) { editArea.setCaretPosition(k); editArea.select(k,k+strB.length()); } else { JOptionPane.showMessageDialog(null,"找不到您查找的内容!","查找",JOptionPane.INFORMATION_MESSAGE); } } } }); //创建"查找"对话框的界面 JPanel panel1=new JPanel(); JPanel panel2=new JPanel(); JPanel panel3=new JPanel(); JPanel directionPanel=new JPanel(); directionPanel.setBorder(BorderFactory.createTitledBorder("方向")); //设置directionPanel组件的边框; //BorderFactory.createTitledBorder(String title)创建一个新标题边框,使用默认边框(浮雕化) //、默认文本位置(位于顶线上)、默认调整 (leading) 以及由当前外观确定的默认字体和文本颜色,并指定了标题文本。 directionPanel.add(upButton); directionPanel.add(downButton); panel1.setLayout(new GridLayout(2,1)); panel1.add(findNextButton); panel2.add(findContentLabel); panel2.add(findText); panel2.add(panel1); panel3.add(matchCheckBox); panel3.add(directionPanel); con.add(panel2); con.add(panel3); findDialog.setSize(410,180); findDialog.setResizable(false);//不可调整大小 findDialog.setLocation(230,280); findDialog.setVisible(true); } if(e.getSource()==replace) { final JDialog replaceDialog=new JDialog(this,"替换",false);//false时允许其他窗口同时处于激活状态(即无模式) Container con=replaceDialog.getContentPane();//返回此对话框的contentPane对象 con.setLayout(new FlowLayout(FlowLayout.CENTER)); JLabel findContentLabel=new JLabel("查找内容(N):"); final JTextField findText=new JTextField(15); JButton findNextButton=new JButton("查找下一个(F):"); JLabel replaceLabel=new JLabel("替换为(P):"); final JTextField replaceText=new JTextField(15); JButton replaceButton=new JButton("替换(R)"); JButton replaceAllButton=new JButton("全部替换(A)"); JButton cancel=new JButton("取消"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { replaceDialog.dispose(); } }); final JCheckBox matchCheckBox=new JCheckBox("区分大小写(C)"); ButtonGroup bGroup=new ButtonGroup(); final JRadioButton upButton=new JRadioButton("向上(U)"); final JRadioButton downButton=new JRadioButton("向下(U)"); downButton.setSelected(true); bGroup.add(upButton); bGroup.add(downButton); /*ButtonGroup此类用于为一组按钮创建一个多斥(multiple-exclusion)作用域。 使用相同的 ButtonGroup 对象创建一组按钮意味着“开启”其中一个按钮时,将关闭组中的其他所有按钮。*/ /*JRadioButton此类实现一个单选按钮,此按钮项可被选择或取消选择,并可为用户显示其状态。 与 ButtonGroup 对象配合使用可创建一组按钮,一次只能选择其中的一个按钮。 (创建一个 ButtonGroup 对象并用其 add 方法将 JRadioButton 对象包含在此组中。)*/ //"查找下一个"按钮监听 findNextButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //"区分大小写(C)"的JCheckBox是否被选中 int k=0,m=0; final String str1,str2,str3,str4,strA,strB; str1=editArea.getText(); str2=findText.getText(); str3=str1.toUpperCase(); str4=str2.toUpperCase(); if(matchCheckBox.isSelected())//区分大小写 { strA=str1; strB=str2; } else//不区分大小写,此时把所选内容全部化成大写(或小写),以便于查找 { strA=str3; strB=str4; } if(upButton.isSelected()) { if(editArea.getSelectedText()==null) k=strA.lastIndexOf(strB,editArea.getCaretPosition()-1); else k=strA.lastIndexOf(strB, editArea.getCaretPosition()-findText.getText().length()-1); if(k>-1) { editArea.setCaretPosition(k); editArea.select(k,k+strB.length()); } else { JOptionPane.showMessageDialog(null,"找不到您查找的内容!","查找",JOptionPane.INFORMATION_MESSAGE); } } else if(downButton.isSelected()) { if(editArea.getSelectedText()==null) k=strA.indexOf(strB,editArea.getCaretPosition()+1); else k=strA.indexOf(strB, editArea.getCaretPosition()-findText.getText().length()+1); if(k>-1) { //String strData=strA.subString(k,strB.getText().length()+1); editArea.setCaretPosition(k); editArea.select(k,k+strB.length()); } else { JOptionPane.showMessageDialog(null,"找不到您查找的内容!","查找",JOptionPane.INFORMATION_MESSAGE); } } } });//"查找下一个"按钮监听结束 //"替换"按钮监听 replaceButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(findText.getText().length()==0) { JOptionPane.showMessageDialog(replaceDialog,"请填写查找内容!","提示",JOptionPane.WARNING_MESSAGE); findText.requestFocus(true); return; } if(replaceText.getText().length()>0 && editArea.getSelectedText()!=null) editArea.replaceSelection(replaceText.getText());//用给定的字符串替换当前选择的内容 } });//"替换"按钮监听结束 //"全部替换"按钮监听 replaceAllButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { editArea.setCaretPosition(0); //将光标放到编辑区开头 int k=0,m=0,replaceCount=0; if(findText.getText().length()==0) { JOptionPane.showMessageDialog(replaceDialog,"请填写查找内容!","提示",JOptionPane.WARNING_MESSAGE); findText.requestFocus(true); return; } while(k>-1)//当文本中有内容被选中时(k>-1被选中)进行替换,否则不进行while循环 { //"区分大小写(C)"的JCheckBox是否被选中 //int k=0,m=0; final String str1,str2,str3,str4,strA,strB; str1=editArea.getText(); str2=findText.getText(); str3=str1.toUpperCase(); str4=str2.toUpperCase(); if(matchCheckBox.isSelected())//区分大小写 { strA=str1; strB=str2; } else//不区分大小写,此时把所选内容全部化成大写(或小写),以便于查找 { strA=str3; strB=str4; } if(upButton.isSelected()) { //k=strA.lastIndexOf(strB,editArea.getCaretPosition()-1); if(editArea.getSelectedText()==null) k=strA.lastIndexOf(strB,editArea.getCaretPosition()-1); else k=strA.lastIndexOf(strB, editArea.getCaretPosition()-findText.getText().length()-1); if(k>-1) { editArea.setCaretPosition(k); editArea.select(k,k+strB.length()); } else { if(replaceCount==0) { JOptionPane.showMessageDialog(replaceDialog, "找不到您查找的内容!", "记事本",JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(replaceDialog,"成功替换"+replaceCount+"个匹配内容!","替换成功",JOptionPane.INFORMATION_MESSAGE); } } } else if(downButton.isSelected()) { if(editArea.getSelectedText()==null) k=strA.indexOf(strB,editArea.getCaretPosition()+1); else k=strA.indexOf(strB, editArea.getCaretPosition()-findText.getText().length()+1); if(k>-1) { editArea.setCaretPosition(k); editArea.select(k,k+strB.length()); } else { if(replaceCount==0) { JOptionPane.showMessageDialog(replaceDialog, "找不到您查找的内容!", "记事本",JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(replaceDialog,"成功替换"+replaceCount+"个匹配内容!","替换成功",JOptionPane.INFORMATION_MESSAGE); } } } if(replaceText.getText().length()==0 && editArea.getSelectedText()!= null) { editArea.replaceSelection(""); replaceCount++; } if(replaceText.getText().length()>0 && editArea.getSelectedText()!= null) { editArea.replaceSelection(replaceText.getText()); replaceCount++; } }//while循环结束 } });//"替换全部"方法结束 //创建"替换"对话框的界面 JPanel directionPanel=new JPanel(); directionPanel.setBorder(BorderFactory.createTitledBorder("方向")); //设置directionPanel组件的边框; directionPanel.add(upButton); directionPanel.add(downButton); JPanel panel1=new JPanel(); JPanel panel2=new JPanel(); JPanel panel3=new JPanel(); JPanel panel4=new JPanel(); panel4.setLayout(new GridLayout(2,1)); panel1.add(findContentLabel); panel1.add(findText); panel1.add(findNextButton); panel4.add(replaceButton); panel4.add(replaceAllButton); panel2.add(replaceLabel); panel2.add(replaceText); panel2.add(panel4); panel3.add(matchCheckBox); panel3.add(directionPanel); panel3.add(cancel); con.add(panel1); con.add(panel2); con.add(panel3); replaceDialog.setSize(420,220); replaceDialog.setResizable(false);//不可调整大小 replaceDialog.setLocation(230,280); replaceDialog.setVisible(true); } } public void checkMenuItemEnabled() { String selectText=editArea.getSelectedText(); if(selectText==null) { cut.setEnabled(false); popupMenu_Cut.setEnabled(false); copy.setEnabled(false); popupMenu_Copy.setEnabled(false); // delete.setEnabled(false); popupMenu_Delete.setEnabled(false); } else { cut.setEnabled(true); popupMenu_Cut.setEnabled(true); copy.setEnabled(true); popupMenu_Copy.setEnabled(true); //editMenu_Delete.setEnabled(true); popupMenu_Delete.setEnabled(true); } //粘帖功能可用性判断 Transferable contents=clipBoard.getContents(this); if(contents==null) { paste.setEnabled(false); popupMenu_Paste.setEnabled(false); } else { paste.setEnabled(true); popupMenu_Paste.setEnabled(true); } }//方法checkMenuItemEnabled()结束 @Override public void changedUpdate(DocumentEvent e) { // TODO Auto-generated method stub } @Override public void insertUpdate(DocumentEvent e) { // TODO Auto-generated method stub } @Override public void removeUpdate(DocumentEvent e) { // TODO Auto-generated method stub } }