java下拉菜单添加事件的问题。做个点击 文件——新建,就能产生一个文本框的小程序。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class NoteBook extends JFrame implements ItemListener
{
private JDesktopPane jDesktopPane;
private JMenu jmenu1,jmenu2,jmenu3;
private JMenuBar jmb;
private JMenuItem jmi1,jmi2,jmi3,jmi4,jmi5;
int count = 1;
NoteBook()
{
super("NoteBook");
Container contentPane = this.getContentPane();
jDesktopPane = new JDesktopPane();
//jta = new JTextArea(50,80);
jmenu1 = new JMenu("文件 ");
jmenu2 = new JMenu("编辑 ");
jmenu3 = new JMenu("搜索 ");
jmb = new JMenuBar();
jmi1 = new JMenuItem("新建(N) ");
jmi2 = new JMenuItem("打开(O) ");
jmi3 = new JMenuItem("关闭(S) ");
jmi4 = new JMenuItem("保存(S) ");
jmi5 = new JMenuItem("另存为(A) ");
setJMenuBar(jmb);
contentPane.add(jDesktopPane);
//添加菜单
jmb.add(jmenu1);
jmb.add(jmenu2);
jmb.add(jmenu3);
//添加文件菜单子选项
jmenu1.add(jmi1);
jmenu1.add(jmi2);
jmenu1.add(jmi3);
jmenu1.add(jmi4);
jmenu1.add(jmi5);
jmi1.addItemListener(this);
setVisible(true);
setBounds(100,100,450,700);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent e)
{
JInternalFrame internalFrame = new JInternalFrame("新建文件夹"+(count++),true,true,true,true);
internalFrame.setLocation(20,20);
internalFrame.setSize(200,200);
internalFrame.setVisible(true);
//添加窗体内部组键
Container icontentPane = internalFrame.getContentPane();
JTextArea jtextArea = new JTextArea(20,20);
icontentPane.add(jtextArea);
jDesktopPane.add(internalFrame);
try {
internalFrame.setSelected(true);
}
catch (java.beans.PropertyVetoException ex)
{
System.out.println("Exception while selecting");
}
}
public static void main(String[] args)
{
new NoteBook();
}
}
------解决方案--------------------
Java code
jmi1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// ...
}
});