1.记事本
package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.*;
public class Textpad implements ActionListener{
JFrame frame;
JTextArea text;
JMenu menu;
File file;
JMenuBar menubar;
JMenuItem newfile;
JMenuItem openfile;
JMenuItem savafile;
JMenuItem exitfile;
JFileChooser choose;
public Textpad() {
frame = new JFrame("记事本");
text = new JTextArea(30,40);
menu = new JMenu("文件");
menubar = new JMenuBar();
newfile = new JMenuItem("新建(N)",new ImageIcon("d:"+ File.separator + "java" + File.separator + "图标" + File.separator + "新建.png"));
openfile = new JMenuItem("打开(O)",new ImageIcon("d:"+ File.separator + "java" + File.separator + "图标" + File.separator + "打开.png"));
savafile = new JMenuItem("保存(S)",new ImageIcon("d:"+ File.separator + "java" + File.separator + "图标" + File.separator + "保存.png"));
exitfile = new JMenuItem("退出(E)",new ImageIcon("d:"+ File.separator + "java" + File.separator + "图标" + File.separator + "退出.png"));
newfile.setMnemonic('N');
openfile.setMnemonic('O');
savafile.setMnemonic('S');
exitfile.setMnemonic('E');
newfile.setAccelerator(KeyStroke.getKeyStroke('N',java.awt.Event.CTRL_MASK));
openfile.setAccelerator(KeyStroke.getKeyStroke('O',java.awt.Event.CTRL_MASK));
savafile.setAccelerator(KeyStroke.getKeyStroke('S',java.awt.Event.CTRL_MASK));
exitfile.setAccelerator(KeyStroke.getKeyStroke('E',java.awt.Event.CTRL_MASK));
menu.add(newfile);
menu.add(openfile);
menu.add(savafile);
menu.add(exitfile);
menubar.add(menu);
newfile.addActionListener(this);
openfile.addActionListener(this);
savafile.addActionListener(this);
exitfile.addActionListener(this);
frame.setJMenuBar(menubar);
frame.setVisible(true);
frame.setSize(400,300);
frame.setLocation(300, 200);
frame.add(text);
}
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if(obj instanceof JMenuItem) {
JMenuItem item = (JMenuItem)obj;
if(item == newfile) {
new Textpad();
}
else if(item == openfile) {
choose = new JFileChooser();
choose.showOpenDialog(null);
file = choose.getSelectedFile();
try {
FileInputStream fis = new FileInputStream(file);
byte b[] = new byte[fis.available()];
fis.read(b);
fis.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if(item == savafile) {
choose = new JFileChooser();
choose.showSaveDialog(null);
}
else if(item == exitfile) {
System.exit(1);
}
}
}
public static void main(String args[]) {
new Textpad();
}
}
JMenuBar:
1. JMenuBar表示一个水平的菜单栏,用来管理菜单,不参与用户交互操作;
2. 可通过调用setJMenuBar( )方法将JMenuBar设置在顶级窗口的顶部;
3. 可通过调用add( JMenu menu)方法添加菜单。
JMenu
1. JMenu 表示一个菜单,用来整理菜单项;
2. 通过调用add( )方法可向菜单里面添加菜单项或者菜单、按钮等;
3. 通过调用addSeparator( )方法可向菜单栏里面添加分隔符。
JMenuItem
1. JMenuIten表示菜单项,是菜单系统中最基本的组件;
2. JMenuIten继承AbstractButton类,因此可以把它看作一个按钮。