1. 程式人生 > >Java基礎-簡易記事本開發(開啟與儲存)

Java基礎-簡易記事本開發(開啟與儲存)


簡易記事本開發--開啟與儲存
程式碼:
package Demo;

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.management.RuntimeErrorException;

public class code
{
	public static void main(String[] args) {
		new myMenu();
	}
}

class myMenu
{
	private Frame f;
	private MenuBar mb;
	private TextArea ta;
	private Menu fileMenu;
	private MenuItem closeItem,saveItem,openItem;
	
	private FileDialog opendia,savedia;
	private File file;
	
	public myMenu() {
		init();
	}
	public void init() {
		f = new Frame("my window");
		f.setBounds(300,100,650,600);
		//f.setLayout(new FlowLayout());//佈局
		
		mb = new MenuBar();//選單條
		ta = new TextArea();//區域
		fileMenu = new Menu("檔案");//選單
		openItem = new MenuItem("開啟");
		saveItem = new MenuItem("儲存");
		closeItem = new MenuItem("退出");
		
		fileMenu.add(openItem);
		fileMenu.add(saveItem);
		fileMenu.add(closeItem);
		mb.add(fileMenu);
		
		f.setMenuBar(mb);
		opendia = new FileDialog(f, "我要開啟", FileDialog.LOAD);
		savedia = new FileDialog(f, "我要儲存", FileDialog.SAVE);
		
		f.add(ta);
		myEvent();
		
		f.setVisible(true);
	}
	
	private void myEvent() {
		
		saveItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(file==null) {
					savedia.setVisible(true);
					String dirpath = savedia.getDirectory();
					String filename = savedia.getFile();
					if(dirpath==null || filename==null)
						return ;
					file = new File(dirpath,filename);
				}
				try {
					BufferedWriter bufw = new BufferedWriter(new FileWriter(file));
					String text = ta.getText();
					bufw.write(text);
				} catch (Exception e) {
					throw new RuntimeException("儲存失敗");
				}
				
			}
			
		});
		
		//讀取檔案
		openItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				opendia.setVisible(true);
				String dirpath = opendia.getDirectory();
				String filename = opendia.getFile();
				if(dirpath==null || filename==null)
					return ;
				file = new File(dirpath,filename);
				try {
					BufferedReader bufr = new BufferedReader(new FileReader(file));
					
					String line = null;
					while((line=bufr.readLine())!=null)
						ta.append(line+"\r\n");
				} catch (Exception e2) {
					throw new RuntimeException("讀取失敗");
				}
			}
		});
		
		//程式直接結束
		closeItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
		
		f.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}
}

如何匯出可執行的jar包:https://blog.csdn.net/sndamhming/article/details/56008795