用Java试编程设计一个下拉式菜单
用Java试编程设计一个下拉式菜单,菜单标题为“设置窗体背景色”,菜单中包含4个选项:红色、绿色、蓝色、退出,并在“蓝色”和“退出”选项间加一条分隔线。给菜单项注册事件监...
用Java试编程设计一个下拉式菜单,菜单标题为“设置窗体背景色”,菜单中包含4个选项:红色、绿色、蓝色、退出,并在“蓝色”和“退出”选项间加一条分隔线。给菜单项注册事件监听器并实现相应的功能。
展开
展开全部
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* @author Hardneedl
*/
final class MenuDemo extends JFrame {
public String getTitle() {return "MenuDemo";}
static private final Dimension size = new Dimension(600,400);
public Dimension getPreferredSize() {return size;}
public Dimension getMaximumSize() {return size;}
public Dimension getMinimumSize() {return size;}
public Dimension getSize(){return size;}
private JPanel colorPane;
MenuDemo() throws HeadlessException {
super();
init();
attachListeners();
doLay();
}
private void init(){
colorPane = new JPanel() {
public boolean isOpaque() {return true;}
};
colorPane.setBackground(Color.PINK);
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("设置窗体背景色");
menu.add(new ColorChangeAction("红色", Color.RED));
menu.add(new ColorChangeAction("绿色", Color.GREEN) );
menu.add(new ColorChangeAction("蓝色", Color.BLUE) );
menu.addSeparator();
menu.add(new ExitAction());
bar.add(menu);
setJMenuBar(bar);
}
private void attachListeners(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void doLay(){
Container c = getContentPane();
c.add(colorPane,BorderLayout.CENTER);
pack();
setVisible(true);
}
private class ColorChangeAction extends AbstractAction{
private Color c;
private ColorChangeAction(String name,Color c) {
super(name);
this.c=c;
}
public void actionPerformed(ActionEvent e) {
colorPane.setBackground(c);
}
}
private class ExitAction extends AbstractAction{
private ExitAction() {super("退出");}
public void actionPerformed(ActionEvent e) {System.exit(1);}
}
public static void main(String...args) {
System.setProperty("swing.defaultlaf","com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.invokeLater(
new Runnable(){
public void run() {
new MenuDemo();
}
}
);
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询