public class MyNotepad {
static JFrame frame;
static JScrollPane textScroll = null;
static JTextArea textArea = null;
public static final int FRAME_WIDTH = 300;
public static final int FRAME_HEIGHT = 300;
public static final void init() {
frame = new JFrame("记事本");
// ImageIcon image = new ImageIcon("src/myPicture.jpg");
// frame.setIconImage(image.getImage());
// 1、菜单条
MenuBar menuBar = new MenuBar();
frame.setMenuBar(menuBar);
// 2、创建菜单
Menu fileMenu = new Menu("文件(F)");
Menu editMenu = new Menu("编辑(E)");
Menu formatMenu = new Menu("格式(O)");
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(formatMenu);
// 3、文件子菜单项
MenuItem openFile = new MenuItem("打开文件", new MenuShortcut(0x4F, true));
MenuItem newFile = new MenuItem("新建", new MenuShortcut(0x4E, true));
MenuItem save = new MenuItem("保存", new MenuShortcut(0x53, false));
MenuItem saveAs = new MenuItem("另存为", new MenuShortcut(0x53, true));
MenuItem close = new MenuItem("关闭", new MenuShortcut(0x57, false));
MenuItem exit = new MenuItem("退出");
fileMenu.add(newFile);
fileMenu.add(openFile);
fileMenu.insertSeparator(2);
fileMenu.add(close);
fileMenu.insertSeparator(4);
fileMenu.add(save);
fileMenu.add(saveAs);
fileMenu.add(exit);
// 创建文本域
textArea = new JTextArea(300, 300);
// 创建滚动条
textScroll = new JScrollPane(textArea);
frame.add(textScroll, BorderLayout.CENTER);
// 创建标签
final JTextField textfield = new JTextField(3);
JPanel northpanel = new JPanel();
JPanel southpanel = new JPanel();
northpanel.setLayout(new GridLayout(7, 7));
northpanel.add(new JLabel("category name:"));
northpanel.add(textfield);
frame.add(northpanel, BorderLayout.NORTH);
JButton inserButton = new JButton("添加");
southpanel.add(inserButton);
inserButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
textArea.append("<category name=" + textfield.getText() + " > "
+ "\n" + "<rulegroup id=");
}
});
frame.add(southpanel, BorderLayout.SOUTH);
// 1、打开文件处理事件
openFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FileDialog openFileDialog = new FileDialog(frame, "打开",
FileDialog.LOAD);
openFileDialog.setVisible(true);
textArea.setVisible(true);
// 得到文件名
String openedFileName = openFileDialog.getFile();
String openedFileDirectory = openFileDialog.getDirectory();
String openedFilePath = openedFileDirectory + openedFileName;
if (openedFileName.equals("") || openedFileName == null) {
frame.setTitle("无标题 - 记事本");
} else {
frame.setTitle(openedFileName + " - 记事本");
}
try {
writerBuffertoJTextArea(openedFilePath, textArea);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
// 2、 新建事件处理
newFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
textArea.setVisible(true);
frame.setTitle("无标题 - 记事本");
textArea.setText("");
}
});
// 3、 关闭文件事件
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textArea.setVisible(false);
// textArea = null;
}