import java.awt.event.*
import javax.swing.*
public class MyMenu extends JFrame{
JMenuBar jmbar=new JMenuBar()
JMenu jmenu=new JMenu("颜色")
JMenuItem jmt1=new JMenuItem("红色"),
jmt2=new JMenuItem("黄色"),
jmt3=new JMenuItem("蓝色")
JPanel jp=new JPanel()
MyMenu(){
setTitle("菜单测试")
setSize(400,300)
setJMenuBar(jmbar)
jmbar.add(jmenu)
jmenu.add(jmt1)
jmenu.add(jmt2)
jmenu.add(jmt3)
add(jp)
jmt1.addActionListener(new MenuAction(this))
jmt2.addActionListener(new MenuAction(this))
jmt3.addActionListener(new MenuAction(this))
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
setVisible(true)
}
public static void main(String[] args) {
new MyMenu()
}
}
class MenuAction implements ActionListener{
MyMenu m
MenuAction(MyMenu m){
this.m=m
}
public void actionPerformed(ActionEvent e){
String color=e.getActionCommand()
if(color=="红色")m.jp.setBackground(Color.red)
else if(color=="黄色")m.jp.setBackground(Color.yellow)
else if(color=="蓝色")m.jp.setBackground(Color.blue)
}
}
不知道你要什么事件代码,我写了个比较简单的你看适合不。
因为没有使用布局 你可以先搞两个按钮b1,b2然后这么写
jf.add(b1,BorderLayout.WEST)
jf.add(b2,BorderLayout.EAST)
你会发现一个在左边一个在右边 因为JFrame默认是BorderLayout布局
布局还有很多东西 你多了解一下就清楚了