第二次作业:WinForm程序设计-简易记事本程序

Notepad.java

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

@SuppressWarnings("serial")
public class Notepad extends JFrame {

	public static final int DEFAULT_WIDTH = 400;
	public static final int DEFAULT_HEIGHT = 300;
	private JTextArea text = new JTextArea();
	private JFileChooser fileChooser = new NotepadFileChooser();
	private File currentFile = null;
	private boolean edit = false;
	
	public Notepad() {
		setTitle("记事本");
		setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
		setJMenuBar(createMenuBar());
		add(new JScrollPane(text), BorderLayout.CENTER);
		text.setFont(new Font("Fixedsys", Font.BOLD, 12));
		text.addKeyListener(new KeyAdapter() {
			public void keyTyped(KeyEvent event) {
				Notepad.this.edit = true;
			}
		});
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent event) {
				try {
					if (edit) {
						int t = JOptionPane.showConfirmDialog(Notepad.this, "是否保存文件?", "警告!", JOptionPane.YES_NO_OPTION);
						if (t == JOptionPane.OK_OPTION) {
							save();
						}
					}
					System.exit(0);
				} catch (IOException e) {
					JOptionPane.showMessageDialog(Notepad.this, "保存文件失败!");
				}
			}
		});
	}
	
	private JMenuBar createMenuBar() {
		JMenu file = new JMenu("文件(F)");
		file.setMnemonic('F');
		
		JMenuItem menuItem;
		menuItem = file.add(new NewAction());
		menuItem.setAccelerator(KeyStroke.getKeyStroke("ctrl N"));
		menuItem.setMnemonic('N');
		menuItem = file.add(new OpenAction());
		menuItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
		menuItem.setMnemonic('O');
		menuItem = file.add(new SaveAction());
		menuItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));
		menuItem.setMnemonic('S');
		menuItem = file.add(new SavaAsAction());
		menuItem.setAccelerator(KeyStroke.getKeyStroke("ctrl A"));
		menuItem.setMnemonic('A');
		file.addSeparator();
		menuItem = file.add(new ExitAction());
		menuItem.setMnemonic('X');
		
		JMenuBar menuBar = new JMenuBar();
		menuBar.add(file);
		return menuBar;
	}
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				JFrame frame = new Notepad();
				//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				frame.setLocationByPlatform(true);
				frame.pack();
				frame.setVisible(true);
			}
		});
	}
	
	private class NewAction extends AbstractAction {
		
		public NewAction() {
			super("新建(N)");
		}
		
		public void actionPerformed(ActionEvent event) {
			if (edit) {
				try {
					int t = JOptionPane.showConfirmDialog(Notepad.this, "是否保存文件?");
					if (t == JOptionPane.OK_OPTION) {
						save();
					} else if (t == JOptionPane.CANCEL_OPTION) {
						return;
					}
					text.setText("");
					currentFile = null;
					edit = false;
				}catch (IOException e) {
					JOptionPane.showMessageDialog(Notepad.this, "文件保存失败!");
				}
			} else {
				text.setText("");
				currentFile = null;
				edit = false;
			}
		}
	} 

	private class OpenAction extends AbstractAction {

		public OpenAction() {
			super("打开(O)");
		}

		public void actionPerformed(ActionEvent event) {
			if (edit) {
				try {
					int t = JOptionPane.showConfirmDialog(Notepad.this, "是否保存文件?"); 
					if (t == JOptionPane.OK_OPTION) {
						save();
					} else if (t == JOptionPane.CANCEL_OPTION) {
						return;
					}
				}catch (IOException e) {
					JOptionPane.showMessageDialog(Notepad.this, "文件保存失败!");
				}
			}
			if (fileChooser.showOpenDialog(Notepad.this) ==	JFileChooser.APPROVE_OPTION) {
				currentFile = fileChooser.getSelectedFile();
				try {
					readFile();
					edit = false;
				} catch (IOException e) {
					JOptionPane.showMessageDialog(Notepad.this, "文件打开失败!");
				}
			}				
		}
	}

	private class SaveAction extends AbstractAction {
		
		public SaveAction() {
			super("保存(S)");
		}

		public void actionPerformed(ActionEvent event) {
			try {
				save();
			}catch (IOException e) {
				JOptionPane.showMessageDialog(Notepad.this, "文件保存失败!");
			} 			
		}
	}
	
	private class SavaAsAction extends AbstractAction {
		
		public SavaAsAction() {
			super("另存为(A)");
		}
		
		public void actionPerformed(ActionEvent event) {
			try {
				currentFile = null;
				save();
			} catch (IOException e) {
				JOptionPane.showMessageDialog(Notepad.this, "文件保存失败!");
			}
		}
	}

	private class ExitAction extends AbstractAction {
		
		public ExitAction() {
			super("退出(X)");
		}

		public void actionPerformed(ActionEvent event) {
			try {
				if (edit) {
					int t = JOptionPane.showConfirmDialog(Notepad.this, "是否保存文件?");
					if (t == JOptionPane.OK_OPTION) {
						save();
					} else if (t == JOptionPane.CANCEL_OPTION) {
						return;
					}
				}
				System.exit(0);
			}catch (IOException e) {
				JOptionPane.showMessageDialog(Notepad.this, "文件保存失败!");
			}		
		}
	}

	private void writeFile() throws IOException {
		PrintWriter out = new PrintWriter(currentFile);
		BufferedReader in = new BufferedReader(new StringReader(text.getText()));
		String str;
		while ((str = in.readLine()) != null) {
			out.println(str);
		}
		in.close();
		out.close();
	}
	
	private void readFile() throws IOException {
		BufferedReader in = new BufferedReader(new FileReader(currentFile));
		text.setText("");
		String str;
		while ((str = in.readLine()) != null) {
			text.append(str);
			text.append("/n");
		}
		in.close();
	}
	
	private void save() throws IOException {
		if (currentFile != null) {
			writeFile();
			edit = false;
		}else if (fileChooser.showSaveDialog(Notepad.this) == JFileChooser.APPROVE_OPTION) {
			if (fileChooser.getFileFilter().getDescription().equals("文本文件(*.txt)")) {
				currentFile = new File(fileChooser.getSelectedFile().getName() + ".txt");
			} else {
				currentFile = fileChooser.getSelectedFile();
			}
			writeFile();
			edit = false;
		}
	}
}


NotepadFileChooser.java

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.*;

@SuppressWarnings("serial")
public class NotepadFileChooser extends JFileChooser {

	public NotepadFileChooser() {
		super();
		setAcceptAllFileFilterUsed(true);
		this.addChoosableFileFilter(new MyFileFilter(new String[] {".txt"}, "文本文件(*.txt)"));
	}
	
	private class MyFileFilter extends FileFilter {
		
		private String[] suffixes;
		private String description;
		
		public MyFileFilter(String[] aSuffixes, String aDescription) {
			suffixes = aSuffixes;
			description = aDescription;
		}
		
		public boolean accept(File file) {
			for (String suffix : suffixes) {
				if (file.getName().toLowerCase().endsWith(suffix.toLowerCase())) {
					return true;
				}
			}
			return file.isDirectory();
		}
		
		public String getDescription() {
			return description;
		}
	}
}


将两个java文件放在同一个文件夹里,运行结果如下:


按左上方的“文件”选项:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值