日期:2014-05-20  浏览次数:21033 次

java菜单选项事件怎么处理
import javax.swing.*;
import java.awt.event.*;
public class Test2 implements ActionListener,MouseListener{
int j;
int n=3;
JFrame jf;
JPanel jp;
JLabel jl1,jl2,jl3,jl4;
JTextField jt;
JButton jb1,jb2,jb3;
public static void main(String []args){
Test2 t=new Test2();
t.run();
}
public void run(){
jf=new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar jmb=new JMenuBar();
JMenu jm1=new JMenu("设置");
JMenu jm2=new JMenu("排行榜");
JMenu jm3=new JMenu("帮助");
JMenuItem jmi1=new JMenuItem("初级(3以内)");
jmi1.addMouseListener(this);
JMenuItem jmi2=new JMenuItem("中级(10以内)");
jmi2.addMouseListener(this);
JMenuItem jmi3=new JMenuItem("高级(100以内)");
jmi3.addMouseListener(this);
JMenuItem jmi4=new JMenuItem("退出");
JMenuItem jmi5=new JMenuItem("显示榜单");
JMenuItem jmi6=new JMenuItem("说明");
JMenuItem jmi7=new JMenuItem("帮助");
jmb.add(jm1);
jmb.add(jm2);
jmb.add(jm3);
jm1.add(jmi1);
jm1.add(jmi2);
jm1.add(jmi3);
jm1.addSeparator();
jm1.add(jmi4);
jm2.add(jmi5);
jm3.add(jmi6);
jm3.add(jmi7);
jf.setJMenuBar(jmb);
jp=new JPanel();
jl1=new JLabel("未出题 ");
jl2=new JLabel("已出题 ");
jl3=new JLabel("请输入你猜得数");
jl4=new JLabel();
jt=new JTextField(5);
jb1=new JButton("出题");
jb1.addActionListener(this);
jb2=new JButton("确定");
jb2.addActionListener(this);
jb3=new JButton("答案");
jb3.addActionListener(this);
jp.add(jb1);
jp.add(jl1);
jp.add(jl2);
jl2.setVisible(false);
jp.add(jl4);
jp.add(jl3);
jp.add(jt);
jp.add(jb2);
jp.add(jb3);
jf.add(jp);
jf.setSize(350,150);
jf.setLocation(500,400);
jf.setVisible(true);
}
public int random(){
int i=(int)(n*Math.random()+1);
return(i);
}
public void actionPerformed(ActionEvent e){
int jb=Integer.parseInt(jt.getText());
if(e.getSource()==jb1){
int c=new Test2().random();
this.j=c;
jl1.setVisible(false);
jl2.setVisible(true);
}
if(e.getSource()==jb2){
JDialog jd=new JDialog(jf,"",true);
jd.setSize(200,100);
if(jb==j){
jd.add(new JLabel("恭喜你,你猜对了"));
}
if(jb<j){
jd.add(new JLabel("不好意思,小额了"));
}
if(jb>j){
jd.add(new JLabel("不好意思,大了"));
}

jd.setVisible(true);
}
if(e.getSource()==jb3){
String s=String.valueOf(j);
jl4.setText(s);
}
//if(e.getSource()==jmi1){}
}
public void mouseClicked(MouseEvent e) {
if(e.getSource()==jmi1){}错误 }
public void mousePressed(MouseEvent e) {

}
public void mouseReleased(MouseEvent e){

}
public void mouseEntered(MouseEvent e){

}
public void mouseExited(MouseEvent e) {

}
}
我的那怎么错了



------解决方案--------------------
菜单项
Java code

Action exitAction = new AbstractAction("退出"){
    public void actionPerformed(ActionEvent e){
        System.exit(0);
    }
};

jm1.add(exitAction);
JToolBar toolbar = new JToolBar();
toolbar.add(exitAction);