記事本

託帕發表於2018-09-20
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class Test extends JFrame implements ActionListener{

	JMenuBar cd;
	JMenu cd1,cd2;
	JMenuItem cdx2,cdx3;
	JTextArea wby;

	public static void main(String[] args){

		Test lx=new Test();	
	}

	public Test(){

		cd=new JMenuBar();
		cd1=new JMenu("檔案(F)");
		cd1.setMnemonic('F');
		cd2=new JMenu("編輯(E)");
		cd2.setMnemonic('E');

		cdx2=new JMenuItem("開啟",new ImageIcon("image/開啟.jpg"));
		cdx2.addActionListener(this);
		cdx2.setActionCommand("open");

		cdx3=new JMenuItem("儲存",new ImageIcon("image/儲存.jpg"));
		cdx3.addActionListener(this);
		cdx3.setActionCommand("save");

		wby=new JTextArea();

		cd1.add(cdx2);   cd1.add(cdx3);
		cd.add(cd1);    cd.add(cd2);

		this.setJMenuBar(cd);
		this.add(wby);


		this.setIconImage((new ImageIcon("image/新建.jpg")).getImage());//左標籤欄新增小圖示   
		this.setTitle("記事本");
		this.setSize(700,500);
		this.setLocation(300,280);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);	
	}


	public void actionPerformed(ActionEvent e) {

		if(e.getActionCommand().equals("open")){

			JFileChooser wjxz=new JFileChooser();
			wjxz.setDialogTitle("檔案開啟");
			wjxz.showOpenDialog(null);
			wjxz.setVisible(true);

			String wjlj=wjxz.getSelectedFile().getAbsolutePath();
			//得到使用者選擇檔案的路徑
			FileReader wjl=null;
			BufferedReader hcl=null;
			try{
				wjl=new FileReader(wjlj);
				hcl=new BufferedReader(wjl);
				String s="",zfc="";
				while((s=hcl.readLine())!=null){
					zfc+=(s+"\n");
				}
				wby.setText(zfc);
			}catch(Exception aa){

			}
			finally{
				try{
					wjl.close();
					hcl.close();
				}catch(Exception e1){

				}
			}
		}
		else if(e.getActionCommand().equals("save")){

			JFileChooser ljxz=new JFileChooser();
			ljxz.setDialogTitle("另存為");
			ljxz.showSaveDialog(null);
			ljxz.setVisible(true);

			String bclj=ljxz.getSelectedFile().getAbsolutePath();
			try{
				PrintStream pl=new PrintStream(bclj);
				System.setOut(pl);
				System.out.println(this.wby.getText());
			}catch(Exception aa){

			}
		}
	}		

}

1.儲存檔案

2.開啟檔案

相關文章