Command Design Pattern简单的GUI空指针

时间:2012-10-27 17:58:36

标签: java swing design-patterns command-pattern

我有这些类: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();

}

我希望根据菜单中选择的jMenuItem来调用在3个JMenuItems中实现的Execute方法。我该怎么做呢?我是否需要3个jMenuItems的包装类?

1 个答案:

答案 0 :(得分:3)

这种模式对于这些简单的GUI任务来说太过分了,但在你的ActionListener中,你可以这样做:

Command command = (Command) event.getSource();
command.Execute();

说明:由于每个自定义JMenuItem都实现了Command界面,因此可以将其转换为&{从而利用Execute方法。

发生NullPoinerException的原因是JPanel构造函数中未分配Command实例:

public btnRedCommand(JPanel p, String text) {
   this.p = p;
   ...