Java簡單記事本實現

來源:互聯網
上載者:User

 涉及的知識點:GUI介面,IO操作,事件監聽。範例程式碼如下:

package ioTest;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import javax.swing.ImageIcon;import javax.swing.JFileChooser;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JTextArea;public class NotePad extends JFrame implements ActionListener{JTextArea jta=null;JMenuBar jmb=null;JMenu jm=null;JMenuItem jmi=null;JMenuItem jmi2=null;public static void main(String[] args) {NotePad np=new NotePad();}public NotePad(){jta=new JTextArea();jmb=new JMenuBar();jm=new JMenu("檔案");jm.setMnemonic('f');//設定快速鍵jmi=new JMenuItem("開啟",new ImageIcon("D:\\javaSpace\\test_1\\src\\3.gif"));//註冊監聽jmi.addActionListener(this);jmi.setActionCommand("open");jmi2=new JMenuItem("儲存");jmi2.addActionListener(this);jmi2.setActionCommand("save");this.setJMenuBar(jmb);jmb.add(jm);jm.add(jmi);jm.add(jmi2);this.add(jta);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setSize(400,300);this.setVisible(true);}@Overridepublic void actionPerformed(ActionEvent arg0) {if(arg0.getActionCommand().equals("open")){//出現選擇檔案對話方塊JFileChooser jfc=new JFileChooser();jfc.setDialogTitle("請選擇檔案...");int value=jfc.showOpenDialog(null);//按預設顯示jfc.setVisible(true);if(value==JFileChooser.APPROVE_OPTION){String filename=jfc.getSelectedFile().getAbsolutePath();//System.out.println("test");FileReader fr=null;BufferedReader br=null;try{fr=new FileReader(filename);br=new BufferedReader(fr);String s,all = "";while((s=br.readLine())!=null){all+=s+"\r\n";}jta.setText(all);}catch(Exception e){e.printStackTrace();}finally{try {br.close();fr.close();} catch (Exception e2) {}}}else{//點JFileChooser關閉按扭時不做作務處理}}else if(arg0.getActionCommand().equals("save")){//出現儲存對話方塊JFileChooser jfc=new JFileChooser();jfc.setDialogTitle("另存新檔...");int value=jfc.showSaveDialog(null);jfc.setVisible(true);if(value==JFileChooser.APPROVE_OPTION){String filename=jfc.getSelectedFile().getAbsolutePath();FileWriter fw=null;BufferedWriter bw=null;try{fw=new FileWriter(filename);bw=new BufferedWriter(fw);bw.write(jta.getText());}catch(Exception e){e.printStackTrace();}finally{try {bw.close();fw.close();} catch (Exception e2) {}}}else{}}}}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.