java仿windows记事本功能完整版
最近学了Java编程,就编了仿windows系统下的记事本练练手,这个记事本实现了windows系统下的大部分功能,只有很少的部分没有实现,比如撤销命令的不完美,这是本人的能力有限,还有那些JMenuItem的是否可用问题,这只是本人比较偷懒,无心再去实现,希望能够与广大的Java爱好者分享我的代码,共同学习进步,我肯定有不足之处,比如有些代码的重复,代码的布置,以及变量的取名问题,希望广大的Java大牛多提宝贵意见,话不多少,直接上代码!
packageorg.mfy.notepad; importjava.awt.*; importjavax.swing.*; importjava.awt.event.*; importjava.io.*; importjava.text.SimpleDateFormat; importjava.util.Date; importjava.util.HashMap; importjava.util.Map; importjavax.swing.event.*; importjavax.swing.text.BadLocationException; importjavax.swing.undo.*; publicclassMyNotepadextendsJFrame{ //文件的标题 privateStringtitle="无标题"; //菜单栏 privateJPanelmp=newJPanel(); privateJMenuBarmb=newJMenuBar(); privateJMenu file=newJMenu("文件(F)"), edit=newJMenu("编辑(E)"), format=newJMenu("格式(V)"), view=newJMenu("查看(O)"), help=newJMenu("帮助(H)"); //文件 privateJMenuItem newFile=newJMenuItem("新建(N)"), open=newJMenuItem("打开(O)"), save=newJMenuItem("保存(S)"), exit=newJMenuItem("退出(X)"); //编辑 privateJMenuItem undo=newJMenuItem("撤销(U)"), cut=newJMenuItem("剪切(T)"), copy=newJMenuItem("复制(C)"), paste=newJMenuItem("粘贴(P)"), delete=newJMenuItem("删除(L)"), find=newJMenuItem("查找(F)"), replace=newJMenuItem("替换(R)"), goTo=newJMenuItem("转到(G)"), selectAll=newJMenuItem("全选(A)"), time=newJMenuItem("时间/日期(D)"); //格式 privateJMenuItemfont=newJMenuItem("字体(F)"); privateJCheckBoxautoLineWrap=newJCheckBox("自动换行(W)"); //查看 privateJMenuItemstate=newJMenuItem("状态(S)"); //帮助 privateJMenuItem checkHelp=newJMenuItem("查看帮助(H)"), about=newJMenuItem("关于记事本(A)"); //文本域 privateJTextAreatxt=newJTextArea(); //弹出菜单 privateJPopupMenujpm=newJPopupMenu(); //定义弹出窗口的打开状态 privatestaticbooleanisOpen=false; //获取屏幕的尺寸 privateintx=(int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(); privateinty=(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight(); publicMyNotepad(){ //新建 newFile.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ Stringtext=txt.getText(); if(!text.equals("")){ Stringstr[]=text.split("\n"); intresult=JOptionPane.showConfirmDialog(null,"是否将更改保存到"+ title+"?","记事本",JOptionPane.YES_NO_CANCEL_OPTION); if(result==JOptionPane.NO_OPTION){//不保存 txt.setText(""); }elseif(result==JOptionPane.CANCEL_OPTION){}//取消保存 elseif(result==0){//保存 JFileChooserjfc=newJFileChooser(); jfc.setDialogTitle("保存"); intssd=jfc.showSaveDialog(MyNotepad.this); if(ssd==jfc.APPROVE_OPTION){ Filefile=jfc.getSelectedFile(); PrintStreamout=null; try{ out=newPrintStream(newFileOutputStream(file)); }catch(FileNotFoundExceptione1){ //TODOAuto-generatedcatchblock e1.printStackTrace(); } for(Strings:str){ out.print(s+"\r\n"); } out.close(); txt.setText("");; } } } } }); //打开 open.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ JFileChooserjfc=newJFileChooser(); jfc.setDialogTitle("打开"); intresult=jfc.showOpenDialog(MyNotepad.this); if(result==JFileChooser.CANCEL_OPTION){} elseif(result==JFileChooser.APPROVE_OPTION){ Filefile=jfc.getSelectedFile(); BufferedReaderinput=null; try{ input=newBufferedReader(newInputStreamReader(newFileInputStream(file))); }catch(FileNotFoundExceptione1){ //TODOAuto-generatedcatchblock e1.printStackTrace(); } Stringtemp=null; try{ while((temp=input.readLine())!=null){ txt.append(temp+"\n"); } }catch(IOExceptione1){ //TODOAuto-generatedcatchblock e1.printStackTrace(); } try{ input.close(); }catch(IOExceptione1){ //TODOAuto-generatedcatchblock e1.printStackTrace(); } } } }); //保存 save.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ Stringstr[]=txt.getText().split("\n"); JFileChooserjfc=newJFileChooser(); jfc.setDialogTitle("保存"); intssd=jfc.showSaveDialog(MyNotepad.this); if(ssd==jfc.APPROVE_OPTION){ Filefile=jfc.getSelectedFile(); PrintStreamout=null; try{ out=newPrintStream(newFileOutputStream(file)); }catch(FileNotFoundExceptione1){ //TODOAuto-generatedcatchblock e1.printStackTrace(); } for(Strings:str){ out.print(s+"\r\n"); } out.close(); } } }); //退出 exit.addActionListener(newActionListener(){ @Override publicvoidactionPerformed(ActionEvente){ Stringstr=txt.getText(); if(!str.equals("")){ intresult=JOptionPane.showConfirmDialog(null,"退出前是否保存?","退出", JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE); if(result==JOptionPane.YES_OPTION){} if(result==JOptionPane.NO_OPTION){ dispose(); } if(result==JOptionPane.CANCEL_OPTION){} }else{ dispose(); } } }); /** *撤销功能 */ finalUndoManagerundom=newUndoManager(); txt.getDocument().addUndoableEditListener(newUndoableEditListener(){ @Override publicvoidundoableEditHappened(UndoableEditEvente){ undom.addEdit(e.getEdit()); } }); undo.addActionListener(newActionListener(){ @Override publicvoidactionPerformed(ActionEvente){ if(undom.canUndo()){ undom.undo(); } } }); //剪切 cut.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ txt.cut(); } }); //粘贴 paste.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ txt.paste(); } }); //删除 delete.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ intstart=txt.getSelectionStart(); intend=txt.getSelectionEnd(); txt.replaceRange("",start,end); } }); /** *为了更好地访问本类中的属性,所以查找使用内部类 */ //定义查找内部类 classFindDialogextendsJDialog{ privateJPanelpan=newJPanel(); privateJLabellabel=newJLabel("查找内容(N):"); privateJTextFieldtxtf=newJTextField(20); privateJButtonbtnf=newJButton("查找下一个(F)"); privateJButtonbtnc=newJButton("取消"); privateJCheckBoxjcb=newJCheckBox("区分大小写(C)"); privateJRadioButtonjrb1=newJRadioButton("向上(U)"); privateJRadioButtonjrb2=newJRadioButton("向下(D)",true); publicFindDialog(){ super(MyNotepad.this,"查找"); //当文本框中有内容时按钮才起作用 txtf.getDocument().addDocumentListener(newDocumentListener(){ @Override publicvoidinsertUpdate(DocumentEvente){ btnf.setEnabled(true); } @Override publicvoidremoveUpdate(DocumentEvente){ if(txtf.getText().length()==0){ btnf.setEnabled(false); } } @Override publicvoidchangedUpdate(DocumentEvente){ } }); btnf.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ Stringstr=txtf.getText(); Stringtexta=txt.getText(); intstart=0; intend=0; intcaretPosition=txt.getCaretPosition();//记录光标的起始位置 if(jcb.isSelected()){//区分大小写 if(jrb2.isSelected()){//向下查询,如果有光标就从光标的位置开始查找,否则就从选中的文本之后的位置开始查找 start=(txt.getSelectedText()==null?caretPosition:txt.getSelectionEnd()); start=texta.indexOf(str,start); if(start==-1){//如果没有找到 JOptionPane.showMessageDialog(null,"找不到"+str); }else{//如果找到了 end=start+str.length(); txt.select(start,end); } }elseif(jrb1.isSelected()){//向上查询,如果有光标就从光标的位置开始查找,否则就从选中的文本之前的位置开始查找 end=(txt.getSelectedText()==null?caretPosition:txt.getSelectionStart()); Stringsubtext=texta.substring(0,end); start=subtext.lastIndexOf(str,end-1); if(start==-1){ JOptionPane.showMessageDialog(null,"找不到"+str); }else{ end=start+str.length(); txt.select(start,end); } } } if(!jcb.isSelected()){//不区分大小写 texta=texta.toLowerCase(); if(jrb2.isSelected()){//向下查询,如果有光标就从光标的位置开始查找,否则就从选中的文本之后的位置开始查找 start=(txt.getSelectedText()==null?caretPosition:txt.getSelectionEnd()); start=texta.indexOf(str.toLowerCase(),start); if(start==-1){//如果没有找到 JOptionPane.showMessageDialog(null,"找不到"+str); }else{//如果找到了 end=start+str.length(); txt.select(start,end); } }elseif(jrb1.isSelected()){//向上查询,如果有光标就从光标的位置开始查找,否则就从选中的文本之前的位置开始查找 end=(txt.getSelectedText()==null?caretPosition:txt.getSelectionStart()); Stringsubtext=texta.substring(0,end); start=subtext.lastIndexOf(str.toLowerCase(),end-1); if(start==-1){ JOptionPane.showMessageDialog(null,"找不到"+str); }else{ end=start+str.length(); txt.select(start,end); } } } } }); btnc.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ dispose(); isOpen=false; } }); this.setLayout(null); label.setBounds(12,10,80,20); txtf.setBounds(100,10,170,20); btnf.setBounds(280,10,90,20); btnf.setMargin(newInsets(0,0,0,0)); btnf.setEnabled(false);//初始化查找下一个按钮不可选 jcb.setBounds(12,70,110,20); jrb1.setMargin(newInsets(0,0,0,0)); jrb2.setMargin(newInsets(0,0,0,0)); ButtonGroupgroup=newButtonGroup(); group.add(jrb1); group.add(jrb2); pan.add(jrb1); pan.add(jrb2); pan.setBorder(BorderFactory.createTitledBorder("方向")); pan.setBounds(120,40,150,55); btnc.setBounds(280,40,90,20); btnc.setMargin(newInsets(0,0,0,0)); add(btnf); add(label); add(txtf); add(jcb); add(pan); add(btnc); setSize(380,130); setLocation(x/2-190,y/2-65); setResizable(false); setVisible(true); setDefaultCloseOperation(DISPOSE_ON_CLOSE); //每次只能显示一个窗口 addWindowListener(newWindowAdapter(){ publicvoidwindowOpened(WindowEvente){ isOpen=true; } }); addWindowListener(newWindowAdapter(){ publicvoidwindowClosing(WindowEvente){ isOpen=false; } }); } } //查找的监听事件 find.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ if(!isOpen){ newFindDialog(); } } }); //替换内部类 classReplaceDialogextendsJDialog{ privateJLabellabel1=newJLabel("查找内容(N)"); privateJLabellabel2=newJLabel("替换为(P)"); privateJTextFieldfield1=newJTextField(20); privateJTextFieldfield2=newJTextField(20); privateJButtonfind=newJButton("查找下一个(F)"); privateJButtonreplace=newJButton("替换(R)"); privateJButtonreplaceAll=newJButton("全部替换(A)"); privateJButtoncanc=newJButton("取消"); privateJCheckBoxjcb=newJCheckBox("区分大小写(C)"); publicReplaceDialog(){ super(MyNotepad.this,"查找"); this.setLayout(null); label1.setBounds(12,5,80,20); label2.setBounds(12,30,80,20); field1.setBounds(100,5,170,20); field2.setBounds(100,30,170,20); find.setBounds(280,5,90,20); find.setMargin(newInsets(0,0,0,0)); replace.setBounds(280,30,90,20); replace.setMargin(newInsets(0,0,0,0)); replaceAll.setBounds(280,55,90,20); replaceAll.setMargin(newInsets(0,0,0,0)); jcb.setBounds(12,70,105,20); jcb.setMargin(newInsets(0,0,0,0)); canc.setBounds(280,80,90,20); field1.getDocument().addDocumentListener(newDocumentListener(){ //当文本框中有内容时按钮才起作用 @Override publicvoidinsertUpdate(DocumentEvente){ find.setEnabled(true); replace.setEnabled(true); replaceAll.setEnabled(true); } @Override publicvoidremoveUpdate(DocumentEvente){ if(field1.getText().length()==0){ find.setEnabled(false); replace.setEnabled(false); replaceAll.setEnabled(false); } } @Override publicvoidchangedUpdate(DocumentEvente){ } }); //查找下一个按钮 find.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ newfindFunction(); } }); //替换按钮 replace.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ //如果有选中的内容就替换,然后选中下一个要替换的内容,否则先查找要替换的内容 if(txt.getSelectedText()!=null){ txt.replaceSelection(field2.getText()); } newfindFunction(); } }); //替换所有按钮 replaceAll.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ Stringstr=txt.getText(); if(jcb.isSelected()){ str=str.replaceAll(field1.getText(),field2.getText()); }else{ str=str.replaceAll("(?i)"+field1.getText(),field2.getText()); } txt.setText(str); } }); //取消按钮 canc.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ dispose(); isOpen=false; } }); add(label1); add(label2); add(field1); add(field2); find.setEnabled(false); replace.setEnabled(false); replaceAll.setEnabled(false); add(find); add(replace); add(replaceAll); add(jcb); add(canc); setSize(380,130); setLocation(x/2-190,y/2-65); setResizable(false); setVisible(true); setDefaultCloseOperation(DISPOSE_ON_CLOSE); addWindowListener(newWindowAdapter(){ publicvoidwindowOpened(WindowEvente){ isOpen=true; } }); addWindowListener(newWindowAdapter(){ publicvoidwindowClosing(WindowEvente){ isOpen=false; } }); } //替换对话框中查找功能类 /** *为了简化代码,将替换对话框里面的查找功能提取出来,成为一个内部类 */ classfindFunction{ publicfindFunction(){//要替换的字符串的位置 intstart=0; intend=0; intcaretPosition=txt.getCaretPosition(); Stringstr=field1.getText(); Stringtexta=txt.getText(); //区分大小写,向下查询,如果有光标就从光标的位置开始查找,否则就从选中的文本之后的位置开始查找 if(jcb.isSelected()){ start=(txt.getSelectedText()==null?caretPosition:txt.getSelectionEnd()); start=texta.indexOf(str.toLowerCase(),start); if(start==-1){//如果没有找到 JOptionPane.showMessageDialog(null,"找不到"+str); }else{//如果找到了 end=start+str.length(); txt.select(start,end); } }elseif(!jcb.isSelected()){//不区分大小写 texta=texta.toLowerCase(); //向下查询,如果有光标就从光标的位置开始查找,否则就从选中的文本之后的位置开始查找 start=(txt.getSelectedText()==null?caretPosition:txt.getSelectionEnd()); start=texta.indexOf(str.toLowerCase(),start); if(start==-1){//如果没有找到 JOptionPane.showMessageDialog(null,"找不到"+str); }else{//如果找到了 end=start+str.length(); txt.select(start,end); } } } } } replace.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ if(!isOpen){ newReplaceDialog(); } } }); //转到内部类 classGoToDialogextendsJDialog{ privateJLabellabel=newJLabel("行号(L):"); privateJTextFieldfield=newJTextField(); privateJButtongoToBtn=newJButton("转到"); privateJButtoncanBtn=newJButton("取消"); privateintrowNum=0;//行号 publicGoToDialog(){ field.addKeyListener(newKeyAdapter(){ publicvoidkeyTyped(KeyEvente){ if(!(e.getKeyChar()>='0'&&e.getKeyChar()<='9')){ e.consume(); } } }); //转到 goToBtn.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ rowNum=Integer.parseInt(field.getText()); if(rowNum>txt.getLineCount()){ JOptionPane.showMessageDialog(null,"行数超过了总行数","记事本-跳行",JOptionPane.INFORMATION_MESSAGE); field.setText(txt.getLineCount()+""); field.requestFocus();//获取文本域的焦点 field.selectAll(); }else{ intposition=0; try{ position=txt.getLineStartOffset(rowNum-1); }catch(BadLocationExceptione1){ //TODOAuto-generatedcatchblock e1.printStackTrace(); } GoToDialog.this.dispose(); txt.requestFocus(); txt.setCaretPosition(position); } } }); //取消 canBtn.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ dispose(); isOpen=false; } }); setLayout(null); label.setBounds(12,10,100,20); field.setBounds(12,30,230,20); goToBtn.setBounds(85,65,75,20); canBtn.setBounds(167,65,75,20); add(label); add(field); add(goToBtn); add(canBtn); setTitle("转到指定行"); setModal(true);//当对话框弹出时母窗口不可编辑 setSize(270,130); setLocation(x/2-135,y/2-65); setResizable(false); setVisible(true); setDefaultCloseOperation(DISPOSE_ON_CLOSE); addWindowListener(newWindowAdapter(){ publicvoidwindowOpened(WindowEvente){ isOpen=true; } }); addWindowListener(newWindowAdapter(){ publicvoidwindowClosing(WindowEvente){ isOpen=false; } }); } } //转到 goTo.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ if(!isOpen){ newGoToDialog(); } } }); //全选 selectAll.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ txt.requestFocus(); txt.selectAll(); } }); time.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ StringdateTime=null; intpos=txt.getCaretPosition(); dateTime=newSimpleDateFormat("hh:mmyyyy/MM/dd").format(newDate()); txt.insert(dateTime,pos); } }); //自动换行 autoLineWrap.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ if(autoLineWrap.isSelected()){ txt.setLineWrap(true); }else{ txt.setLineWrap(false); } } }); //字体内部类 classFontDialogextendsJDialog{ privateJLabellabel1=newJLabel("字体(F):"); privateJLabellabel2=newJLabel("字形(Y):"); privateJLabellabel3=newJLabel("大小(S):"); privateJLabelinstns=newJLabel("中文示例AaBaCc",JLabel.CENTER); privateJTextFieldfield1=newJTextField(); privateJTextFieldfield2=newJTextField(); privateJTextFieldfield3=newJTextField(); privateStringfonts[]=GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); privateJScrollPanescr1=newJScrollPane(); privateJScrollPanescr2=newJScrollPane(); privateJScrollPanescr3=newJScrollPane(); privateJListfontList=null; privateJListfStyleList=null; privateJListfSizeList=null; privateJButtonokBtn=newJButton("确定"); privateJButtoncancBtn=newJButton("取消"); //示例的显示 privateStringselectedFont="Fixedsys"; privateintselectedStyle=Font.PLAIN; privatefloatselectedSize=16; publicFontDialog(){ fontList=newJList(fonts); //fontStyle Stringstyle[]={"常规","倾斜","粗体","倾斜粗体"}; fStyleList=newJList(style); //fontSize Stringsize[]={"8","9","10","11","12","14","16","18","20","22","24", "26","28","36","48","72","初号","小号","一号","小一","二号", "小二","三号","小三","四号","小四","五号","六号","小六","七号","八号"}; fSizeList=newJList(size); //Jlist中一次只能选择一个选项 fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fStyleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fSizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); scr1.add(fontList); scr2.add(fStyleList); scr3.add(fSizeList); scr1.setViewportView(fontList); scr2.setViewportView(fStyleList); scr3.setViewportView(fSizeList); okBtn.setBounds(250,450,80,30); cancBtn.setBounds(340,450,80,30); label1.setBounds(20,20,50,20); label2.setBounds(205,20,50,20); label3.setBounds(350,20,50,20); instns.setBounds(205,280,215,80); instns.setBorder(BorderFactory.createTitledBorder("示例")); field1.setBounds(20,40,170,20); field2.setBounds(205,40,130,20); field3.setBounds(350,40,70,20); scr1.setBounds(20,60,170,170); scr2.setBounds(205,60,130,170); scr3.setBounds(350,60,70,150); scr1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scr2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); scr3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); //文本框1 field1.addKeyListener(newKeyAdapter(){ publicvoidkeyTyped(KeyEvente){ intcount=0;//文本框中的字符数 Stringstr=null;//保存输入到文本框中的字符 intsize=fontList.getModel().getSize();//fontList中的文本个数 str=field1.getText()+e.getKeyChar()+""; count=str.length(); for(inti=0;i=count){ //判断输入的是否与JList中的内容部分匹配(忽略大小写) if(fontList.getModel().getElementAt(i).substring(0,count).compareToIgnoreCase(str)==0){ fontList.ensureIndexIsVisible(size-i>=10?i+9:size-1); if(fontList.getModel().getElementAt(i).compareToIgnoreCase(str)==0){ fontList.setSelectedIndex(i); } break; } else{ fontList.ensureIndexIsVisible(0); fontList.clearSelection(); } } } } }); //文本框2 field2.addKeyListener(newKeyAdapter(){ publicvoidkeyTyped(KeyEvente){ intcount=0;//文本框中的字符数 Stringstr=null;//保存输入到文本框中的字符 intsize=fStyleList.getModel().getSize();//fontList中的文本个数 str=field2.getText()+e.getKeyChar()+""; count=str.length(); for(inti=0;i=count){ //判断输入的是否与JList中的内容部分匹配(忽略大小写) if(fStyleList.getModel().getElementAt(i).substring(0,count).compareToIgnoreCase(str)==0){ if(fStyleList.getModel().getElementAt(i).compareToIgnoreCase(str)==0){ fStyleList.setSelectedIndex(i); } break; } else{ fStyleList.clearSelection(); } } } } }); //文本框3 field3.addKeyListener(newKeyAdapter(){ publicvoidkeyTyped(KeyEvente){ intcount=0;//文本框中的字符数 Stringstr=null;//保存输入到文本框中的字符 intsize=fSizeList.getModel().getSize();//fontList中的文本个数 str=field3.getText()+e.getKeyChar()+""; count=str.length(); for(inti=0;i=count){ //判断输入的是否与JList中的内容部分匹配(忽略大小写) if(fSizeList.getModel().getElementAt(i).substring(0,count).compareToIgnoreCase(str)==0){ fSizeList.ensureIndexIsVisible(size-i>=9?i+8:size-1); if(fSizeList.getModel().getElementAt(i).compareToIgnoreCase(str)==0){ fSizeList.setSelectedIndex(i); } break; } else{ fSizeList.ensureIndexIsVisible(0); fSizeList.clearSelection(); } } } } }); //设置示例中的文本字体样式 //设置字形与字号对照表 finalMapmap=newHashMap(); map.put("常规",(float)Font.PLAIN); map.put("倾斜",(float)Font.ITALIC); map.put("粗体",(float)Font.BOLD); map.put("倾斜粗体",(float)(Font.ITALIC+Font.BOLD)); map.put("初号",42f); map.put("小号",36f); map.put("一号",26f); map.put("小一",24f); map.put("二号",22f); map.put("小二",18f); map.put("三号",16f); map.put("小三",15f); map.put("四号",14f); map.put("小四",12f); map.put("五号",10.5f); map.put("六号",7.5f); map.put("小六",6.5f); map.put("七号",5.5f); map.put("八号",5f); //字体列表监听事件 fontList.addListSelectionListener(newListSelectionListener(){ @Override publicvoidvalueChanged(ListSelectionEvente){ StringtxtFont=txt.getFont().getName();//获取文本中的字体 selectedFont=fontList.isSelectionEmpty()?txtFont:fontList.getSelectedValue(); instns.setFont(newFont(selectedFont,selectedStyle,(int)selectedSize)); } }); //字体样式监听事件 fStyleList.addListSelectionListener(newListSelectionListener(){ @Override publicvoidvalueChanged(ListSelectionEvente){ inttxtStyle=txt.getFont().getStyle();//获取文本中的字体 selectedStyle=(int)(fStyleList.isSelectionEmpty()?txtStyle:map.get(fStyleList.getSelectedValue())); instns.setFont(newFont(selectedFont,selectedStyle,(int)selectedSize)); } }); //字体大小监听 fSizeList.addListSelectionListener(newListSelectionListener(){ publicvoidvalueChanged(ListSelectionEvente){ inttxtSize=txt.getFont().getSize(); if(!fSizeList.isSelectionEmpty()){ Stringtemp=fSizeList.getSelectedValue(); if(temp.matches("\\d+")){ selectedSize=Integer.parseInt(temp); }else{ selectedSize=map.get(fSizeList.getSelectedValue()); } } instns.setFont(newFont(selectedFont,selectedStyle,(int)selectedSize)); } }); //确定按钮 okBtn.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ txt.setFont(newFont(selectedFont,selectedStyle,(int)selectedSize)); isOpen=false; dispose(); } }); //取消按钮 cancBtn.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ dispose(); isOpen=false; } }); /*classMyRenderextendsDefaultListCellRenderer{ publicComponentgetListCellRendererComponent(JList>list,Objectvalue, intindex,booleanisSelected, booleancellHasFocus){ Stringfont=value.toString(); setFont(newFont(font,Font.PLAIN,12)); returnthis; } }*/ setLayout(null); add(label1); add(label2); add(label3); add(instns); add(field1); add(field2); add(field3); add(scr1); add(scr2); add(scr3); add(okBtn); add(cancBtn); setModal(true);//当对话框弹出时母窗口不可编辑 setSize(440,530); setLocation(x/2-220,y/2-265); setResizable(false); setVisible(true); setDefaultCloseOperation(DISPOSE_ON_CLOSE); addWindowListener(newWindowAdapter(){ publicvoidwindowOpened(WindowEvente){ isOpen=true; } }); addWindowListener(newWindowAdapter(){ publicvoidwindowClosing(WindowEvente){ isOpen=false; } }); } } //字体 font.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ if(!isOpen){ newFontDialog(); } } }); //查看帮助 checkHelp.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ JOptionPane.showMessageDialog(null,"与Windows系统下的帮助相似","帮助",JOptionPane.CLOSED_OPTION); } }); //关于 about.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ JOptionPane.showMessageDialog(null,"仿Windows记事本,初学Java的练手作品","关于",JOptionPane.CLOSED_OPTION); } }); //右键弹出菜单内部类 classpopupListenerextendsMouseAdapter{ privateJPopupMenupopup=null; publicpopupListener(JPopupMenupopup){ this.popup=popup; } publicvoidmouseReleased(MouseEvente){ showPopupMenu(e); } publicvoidmouseClicked(MouseEvente){ showPopupMenu(e); } privatevoidshowPopupMenu(MouseEvente){ if(e.isPopupTrigger()){ //右键弹出菜单 jpm.add(undo); jpm.add(cut); jpm.add(copy); jpm.add(delete); jpm.add(find); jpm.add(replace); jpm.add(goTo); jpm.add(selectAll); jpm.add(time); popup.show(e.getComponent(),e.getX(),e.getY()); } } } //右键弹出菜单 txt.addMouseListener(newpopupListener(jpm)); //设置快捷键 newFile.setAccelerator(KeyStroke.getKeyStroke('N',java.awt.event.InputEvent.CTRL_DOWN_MASK)); open.setAccelerator(KeyStroke.getKeyStroke('O',java.awt.event.InputEvent.CTRL_DOWN_MASK)); save.setAccelerator(KeyStroke.getKeyStroke('S',java.awt.event.InputEvent.CTRL_DOWN_MASK)); undo.setAccelerator(KeyStroke.getKeyStroke('Z',java.awt.event.InputEvent.CTRL_DOWN_MASK)); cut.setAccelerator(KeyStroke.getKeyStroke('X',java.awt.event.InputEvent.CTRL_DOWN_MASK)); copy.setAccelerator(KeyStroke.getKeyStroke('C',java.awt.event.InputEvent.CTRL_DOWN_MASK)); paste.setAccelerator(KeyStroke.getKeyStroke('V',java.awt.event.InputEvent.CTRL_DOWN_MASK)); find.setAccelerator(KeyStroke.getKeyStroke('F',java.awt.event.InputEvent.CTRL_DOWN_MASK)); replace.setAccelerator(KeyStroke.getKeyStroke('H',java.awt.event.InputEvent.CTRL_DOWN_MASK)); goTo.setAccelerator(KeyStroke.getKeyStroke('G',java.awt.event.InputEvent.CTRL_DOWN_MASK)); selectAll.setAccelerator(KeyStroke.getKeyStroke('A',java.awt.event.InputEvent.CTRL_DOWN_MASK)); time.setAccelerator((KeyStroke)KeyStroke.getAWTKeyStroke((char)KeyEvent.VK_F5)); //设置助记键 file.setMnemonic('F'); edit.setMnemonic('E'); format.setMnemonic('O'); view.setMnemonic('V'); help.setMnemonic('H'); newFile.setMnemonic('N'); open.setMnemonic('O'); save.setMnemonic('S'); exit.setMnemonic('X'); undo.setMnemonic('U'); cut.setMnemonic('T'); copy.setMnemonic('C'); paste.setMnemonic('P'); delete.setMnemonic('L'); find.setMnemonic('F'); replace.setMnemonic('R'); goTo.setMnemonic('G'); selectAll.setMnemonic('A'); time.setMnemonic('D'); font.setMnemonic('F'); autoLineWrap.setMnemonic('W'); state.setMnemonic('S'); checkHelp.setMnemonic('H'); about.setMnemonic('A'); txt.setFont(newFont("Fixedsys",Font.PLAIN,16)); txt.setEditable(true); file.add(newFile); file.add(open); file.add(save); file.addSeparator(); file.add(exit); edit.add(undo); edit.addSeparator(); edit.add(cut); edit.add(copy); edit.add(paste); edit.add(delete); edit.addSeparator(); edit.add(find); edit.add(replace); edit.add(goTo); edit.addSeparator(); edit.add(selectAll); edit.add(time); format.add(autoLineWrap); format.add(font); view.add(state); help.add(checkHelp); help.addSeparator(); help.add(about); mb.add(file); mb.add(edit); mb.add(format); mb.add(view); mb.add(help); setJMenuBar(mb); add(mp); add(newJScrollPane(txt)); setVisible(true); setSize(530,640); setLocation(x/2-265,y/2-320); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
packageorg.mfy.notepad; importjavax.swing.UIManager; importjavax.swing.UnsupportedLookAndFeelException; publicclassNotepad{ publicstaticvoidmain(String[]args){ try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(ClassNotFoundException|InstantiationException |IllegalAccessException|UnsupportedLookAndFeelExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } newMyNotepad(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。