gpt4 book ai didi

java - 命令设计模式简单的 GUI 空指针

转载 作者:行者123 更新时间:2023-11-29 05:53:22 25 4
gpt4 key购买 nike

我有这些类:一个 JPanel 扩展、一个接口(interface)和 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 方法,具体取决于从菜单中选择了哪个 jMenuItem。我怎样才能正确地做到这一点?我需要 3 个 jMenuItem 的包装器类吗?

最佳答案

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

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

说明:因为每个自定义 JMenuItem 都实现了 Command 接口(interface),所以它们可以这样转换并因此利用 执行方法。

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

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

关于java - 命令设计模式简单的 GUI 空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13102692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com