java仿windows记事本小程序
本文实例为大家分享了java仿windows记事本小程序的具体代码,供大家参考,具体内容如下
importjava.awt.CheckboxMenuItem; importjava.awt.Font; importjava.awt.Frame; importjava.awt.Menu; importjava.awt.MenuBar; importjava.awt.MenuItem; importjava.awt.MenuShortcut; importjava.awt.TextArea; importjava.awt.Toolkit; importjava.awt.event.ActionEvent; importjava.awt.event.ActionListener; importjava.awt.event.ItemEvent; importjava.awt.event.ItemListener; importjava.awt.event.KeyEvent; importjava.awt.event.WindowAdapter; importjava.awt.event.WindowEvent; importjava.awt.peer.ButtonPeer; importjava.io.BufferedReader; importjava.io.File; importjava.io.FileInputStream; importjava.io.FileNotFoundException; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStreamReader; importjava.io.OutputStream; importjava.io.StringReader; importjava.io.StringWriter; importjava.sql.Date; importjava.text.SimpleDateFormat; importjavax.print.DocFlavor.STRING; importjavax.script.ScriptException; importjavax.swing.BorderFactory; importjavax.swing.BoxLayout; importjavax.swing.ButtonGroup; importjavax.swing.JFileChooser; importjavax.swing.JFrame; importjavax.swing.JOptionPane; importjavax.swing.JPanel; importjavax.swing.JRadioButton; importjavax.swing.JScrollBar; importjavax.swing.JScrollPane; importjavax.swing.JTextArea; importjavax.swing.border.EtchedBorder; importjavax.swing.border.TitledBorder; importjavax.swing.event.AncestorListener; importjavax.swing.filechooser.FileNameExtensionFilter; publicclassCrazy_15_4{ privateJFramef=newJFrame("记事本"); //成员变量 staticStringshearPlate=null; staticbooleanisAutoWrap=true;//是否自动换行 JTextAreata=newJTextArea(20,60); JScrollPanejsp=newJScrollPane(ta); privateMenuBarmb=newMenuBar(); publicStringfontStr="宋体"; publicStringshapeStr="0"; publicStringsizeStr="20"; Fontfont=newFont(fontStr,Integer.parseInt(shapeStr),Integer.parseInt(sizeStr)); //menu Menufile=newMenu("文件"); Menuedit=newMenu("编辑"); Menuformat=newMenu("格式"); //menuitem MenuItemnewItem=newMenuItem("新建"); MenuItemopenItem=newMenuItem("打开"); MenuItemsaveItem=newMenuItem("保存"); MenuItemsaveAsItem=newMenuItem("另存为"); MenuItemcutItem=newMenuItem("剪切"); MenuItemcopyItem=newMenuItem("复制"); MenuItempasteItem=newMenuItem("粘贴"); CheckboxMenuItemautoWrap=newCheckboxMenuItem("自动换行",isAutoWrap); MenuItemFontItem=newMenuItem("字体"); //使用“ctrl+x”快捷键 MenuItemexitIitem=newMenuItem("退出",newMenuShortcut(KeyEvent.VK_X)); publicvoidinit(){ //带滚动条的文本域 ta.setLineWrap(isAutoWrap); jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); file.add(newItem); file.add(openItem); file.add(saveItem); file.add(saveAsItem); edit.add(cutItem); edit.add(copyItem); edit.add(pasteItem); format.add(autoWrap); format.add(FontItem); mb.add(file); mb.add(edit); mb.add(format); f.setMenuBar(mb); f.addWindowListener(newWindowAdapter(){ publicvoidwindowClosing(WindowEventwe){ if(!(ta.getText().equals(""))){ Object[]options={"保存","不保存","取消"}; inta=JOptionPane.showOptionDialog(null,"是否将更改保存到H:/Programing/无标题.txt","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,options,options[0]); if(a==JOptionPane.OK_OPTION){ if(save()){ System.exit(0); } }elseif(a==JOptionPane.NO_OPTION){ System.exit(0); } }else{ System.exit(0); } } }); newItem.addActionListener(newnewListener()); openItem.addActionListener(newopenListener()); saveItem.addActionListener(newsaveListener()); saveAsItem.addActionListener(newsaveAsListener()); cutItem.addActionListener(newcutAsListener()); copyItem.addActionListener(newcopyAsListener()); pasteItem.addActionListener(newpasteAsListener()); autoWrap.addItemListener(newautoWrapAsListener()); FontItem.addActionListener(newfontListener()); ta.setFont(font); //使文本框处在屏幕中间 intwidth=Toolkit.getDefaultToolkit().getScreenSize().width; intheight=Toolkit.getDefaultToolkit().getScreenSize().height; f.add(jsp); f.pack(); f.setLocation(width/2-f.getWidth()/2,height/2-f.getHeight()/2); f.setVisible(true); //避免关闭对话框直接关闭文本文件 f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } publicstaticvoidmain(String[]args){ newCrazy_15_4().init(); } //是否保存 publicvoidsaveOrNot(){ if(!(ta.getText().equals(""))){ Object[]options={"保存","不保存","取消"}; inta=JOptionPane.showOptionDialog(null,"是否将更改保存到H:/Programing/无标题.txt","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,options,options[0]); if(a==JOptionPane.OK_OPTION){ save(); } } } //保存文本文件 publicbooleansave(){ booleanisSaved=false; JFileChooserjf=newJFileChooser(); FileNameExtensionFilterfilter=newFileNameExtensionFilter("txt","txt"); jf.setAcceptAllFileFilterUsed(false); jf.setFileFilter(filter); intvalue=jf.showSaveDialog(null); if(value==JFileChooser.APPROVE_OPTION){ Filefile=jf.getSelectedFile(); Stringstr=ta.getText(); byte[]buf=str.getBytes(); try{ OutputStreamos=newFileOutputStream(file); os.write(buf); os.flush(); os.close(); isSaved=true; }catch(IOExceptione){ e.printStackTrace(); } } returnisSaved; } //新建监听器 classnewListenerimplementsActionListener{ publicvoidactionPerformed(ActionEvente){ if(!(ta.getText().equals(""))){ Object[]options={"保存","不保存","取消"}; inta=JOptionPane.showOptionDialog(null,"是否将更改保存到H:/Programing/无标题.txt","记事本",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE,null,options,options[0]); if(a==JOptionPane.OK_OPTION){ if(save()){ ta.setText(""); } }elseif(a==JOptionPane.NO_OPTION){ ta.setText(""); } } } } //打开监听器,从硬盘目录打开文本文件 classopenListenerimplementsActionListener{ publicvoidactionPerformed(ActionEvente){ JFileChooserjf=newJFileChooser(); FileNameExtensionFilterfilter=newFileNameExtensionFilter("txt","txt"); jf.setAcceptAllFileFilterUsed(false); jf.setFileFilter(filter); intvalue=jf.showOpenDialog(null); if(value==JFileChooser.APPROVE_OPTION){ Filefile=jf.getSelectedFile(); try{ Stringencoding="GBK";//考虑编码格式 InputStreamReaderisr=newInputStreamReader(newFileInputStream(file),encoding); BufferedReaderbr=newBufferedReader(isr); Stringstr=null; while((str=br.readLine())!=null){ ta.append(str); } }catch(FileNotFoundExceptione1){ //TODOAuto-generatedcatchblock e1.printStackTrace(); }catch(IOExceptione1){ //TODOAuto-generatedcatchblock e1.printStackTrace(); } } } } //保存监听器,以电脑时间命名 classsaveListenerimplementsActionListener{ publicvoidactionPerformed(ActionEvente){ Stringname=null; SimpleDateFormatdf=newSimpleDateFormat("yyyy-MM-ddHH-mm-ss"); name=df.format(System.currentTimeMillis()); Filefile=newFile("H:/Programing/workspace/"+name+".txt"); Stringstr=ta.getText(); byte[]buf=str.getBytes(); if(!str.equals("")){ try{ OutputStreamos=newFileOutputStream(file); os.write(buf); os.flush(); os.close(); }catch(IOExceptione2){ e2.printStackTrace(); } } } } //另存为监听器 classsaveAsListenerimplementsActionListener{ publicvoidactionPerformed(ActionEvente){ save(); } } //剪切监听器 classcutAsListenerimplementsActionListener{ publicvoidactionPerformed(ActionEvente){ shearPlate=ta.getSelectedText(); intstartPosi=ta.getSelectionStart(); intendPosi=ta.getSelectionEnd(); StringBuffersb=newStringBuffer(ta.getText()); sb.delete(startPosi,endPosi); ta.setText(sb.toString()); } } //复制监听器 classcopyAsListenerimplementsActionListener{ publicvoidactionPerformed(ActionEvente){ shearPlate=ta.getSelectedText(); } } //粘贴监听器 classpasteAsListenerimplementsActionListener{ publicvoidactionPerformed(ActionEvente){ intposition=ta.getCaretPosition(); StringBuildersb=newStringBuilder(ta.getText()); sb.insert(position,shearPlate); ta.setText(sb.toString()); ta.setCaretPosition(position+shearPlate.length()); } } //自动换行监听器 classautoWrapAsListenerimplementsItemListener{ @Override publicvoiditemStateChanged(ItemEvente){ if(autoWrap.getState()){ isAutoWrap=true; ta.setLineWrap(isAutoWrap); jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); }else{ isAutoWrap=false; ta.setLineWrap(isAutoWrap); jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); } } } //字体监听器 classfontListenerimplementsActionListener{ JFramejf=newJFrame("字体"); JPaneljp=newJPanel(); ButtonPanelfontButton=newButtonPanel("字体",newString[]{"宋体","黑体","楷体","吴祎晗1.0"}); ButtonPanelshapeButton=newButtonPanel("字形",newString[]{"常规","粗体","斜体","粗体&斜体"}); ButtonPanelsizeButton=newButtonPanel("字号",newString[]{"12","16","20","24","26"}); publicvoidactionPerformed(ActionEvente){ jp.setBorder(newTitledBorder(newEtchedBorder(),"字体选择",TitledBorder.CENTER,TitledBorder.TOP)); jp.add(fontButton); jp.add(shapeButton); jp.add(sizeButton); jf.add(jp); jf.pack(); jf.setLocationRelativeTo(f); jf.setVisible(true); jf.addWindowListener(newWindowAdapter(){ publicvoidwindowClosing(WindowEvente){ fontStr=fontButton.getSelec(); sizeStr=sizeButton.getSelec(); font=newFont(fontStr,shapeVal(shapeButton.getSelec()),Integer.parseInt(sizeStr)); ta.setFont(font); } }); } publicintshapeVal(Stringstr){ inta=0; switch(str){ case"常规": a=0; break; case"粗体": a=1; break; case"斜体": a=2; break; case"粗体&斜体": a=3; break; } returna; } } } //定义一个JPanel类扩展类,该类的对象包含多个纵向排列的 //JRadioButton控件,且panel扩展类可以指定一个字符串作为TitledBorder classButtonPanelextendsJPanel{ privateButtonGroupgroup; publicButtonPanel(Stringtitle,String[]options){ setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),title)); setLayout(newBoxLayout(this,BoxLayout.Y_AXIS)); group=newButtonGroup(); for(inti=0;options!=null&&i以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。