【发布时间】:2012-10-17 15:35:37
【问题描述】:
我有这些类:一个 JPanel 扩展、一个接口和 3 个 JmenuItem 类。
public class RedFrame extends javax.swing.JFrame implements ActionListener {
private JMenuBar jMenuBar1;
private JPanel jPanel1;
private fileExitCommand jMenuItem3;
private fileOpenCommand jMenuItem2;
private btnRedCommand jMenuItem1;
private JMenu jMenu1;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
RedFrame inst = new RedFrame();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public RedFrame() {
super();
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
jPanel1 = new JPanel();
getContentPane().add(jPanel1, BorderLayout.CENTER);
}
{
jMenuBar1 = new JMenuBar();
setJMenuBar(jMenuBar1);
{
jMenu1 = new JMenu();
jMenuBar1.add(jMenu1);
jMenu1.setText("Meniu");
{
jMenuItem1 = new btnRedCommand(jPanel1, "RED");
jMenu1.add(jMenuItem1);
}
{
jMenuItem2 = new fileOpenCommand("Open");
jMenu1.add(jMenuItem2);
}
{
jMenuItem3 = new fileExitCommand("Exit");
jMenu1.add(jMenuItem3);
}
}
}
jMenuItem1.addActionListener(this);
jMenuItem2.addActionListener(this);
jMenuItem3.addActionListener(this);
pack();
setSize(300 * 16 / 9, 300);
} catch (Exception e) {
// add your error handling code here
e.printStackTrace();
}
}
@Override
public void actionPerformed(ActionEvent event) {
Execute();
}
}
还有
public class btnRedCommand extends JMenuItem implements Command {
protected JPanel p;
protected String text;
public btnRedCommand(JPanel p, String text) {
p.setBackground(Color.cyan);
this.setText(text);
}
public void Execute() {
// TODO Auto-generated method stub
p.setBackground(Color.red);
}
}
和
public interface Command {
public void Execute();
}
我希望调用 3 个 JMenuItems 中实现的 Execute 方法,具体取决于选择了 Menu 中的哪个 jMenuItem。我怎样才能正确地做到这一点?我需要 3 个 jMenuItem 的包装类吗?
【问题讨论】:
-
为每个菜单项添加一个特定的 ActionListener(总共 3 个不同的 ActionListener),然后忘记 Command。如果您必须执行的代码只是更改 GUI,则不需要抽象层。
-
@ignis 想要这样做是为了了解它是如何完成的,GUI 仅用于演示。
-
是的,就是这样。 3 个不同的任务,3 个不同的听众。除非您必须处理执行某些应用程序逻辑的外部类,否则没有 Command 接口。
-
您的代码让我很困惑,因为您使用的是非标准命名约定,而且您似乎无缘无故地有代码块。另外,这条线会编译吗,
Execute();?我没有看到与此匹配的方法。考虑编辑您的代码,使方法名称全部以小写字母开头,类名称全部以大写字母开头,在应该使用它们的地方使用块,等等......我们都会更容易理解它。 -
@HovercraftFullOfEels 感谢您的关注。问题解决了。注意到您关于命名约定和块的建议。谢谢!
标签: java swing design-patterns command-pattern