Java 在“我的”对话框中按按钮时,未调用actionPerformed
单击为“确定”和“取消”添加的按钮时,不会调用actionPerformed 代码:Java 在“我的”对话框中按按钮时,未调用actionPerformed,java,Java,单击为“确定”和“取消”添加的按钮时,不会调用actionPerformed 代码: 您正在将操作命令设置为: okBut.setActionCommand("ok"); 但我们正在检查: if ("OK".equals(e.getActionCommand())) 这不匹配,因为情况不同。setActionCommand仅在ActionEvent中设置消息。您需要的是addActionListener。我已经更新了你的代码 但是你应该知道的另一件事
您正在将操作命令设置为:
okBut.setActionCommand("ok");
但我们正在检查:
if ("OK".equals(e.getActionCommand()))
这不匹配,因为情况不同。setActionCommand仅在ActionEvent中设置消息。您需要的是addActionListener。我已经更新了你的代码 但是你应该知道的另一件事是没有必要这样做。而是使用JComponent作为消息参数的JOptionPane.showConfirmDialog:它自动执行所有按钮处理和模式在线等待
public dlgEmpty(JFrame parent)
{
super(parent,"Indicators", true);
Container content = getContentPane();
content.setLayout(new BorderLayout());
butPan = Box.createHorizontalBox();
JButton okBut = new JButton("OK");
okBut.setActionCommand("ok");
okBut.addActionListener(this); // added this line
butPan.add(okBut, BorderLayout.SOUTH);
JButton CancelBut = new JButton("Cancel");
CancelBut.setActionCommand("Cancel");
CancelBut.addActionListener(this);
butPan.add(CancelBut, BorderLayout.SOUTH); //added this line
content.add(butPan, BorderLayout.SOUTH);
centerPan = Box.createVerticalBox();
content.add(centerPan, BorderLayout.CENTER);
pack();
show();
}
boolean isOk=false;
public void actionPerformed(ActionEvent e)
{
if ("OK".equals(e.getActionCommand()))
isOk=true;
setVisible(false);
}
}
在何处将ActionListener添加到按钮?1)变量名称不应以大写字符开头2)action命令默认为按钮的文本,因此如果要使用相同的值,则无需显式设置3)每个按钮都有一个唯一的ActionListener是更好的设计,因此您甚至不需要担心动作命令。4) 然后需要将每个ActionListener添加到特定按钮。
public dlgEmpty(JFrame parent)
{
super(parent,"Indicators", true);
Container content = getContentPane();
content.setLayout(new BorderLayout());
butPan = Box.createHorizontalBox();
JButton okBut = new JButton("OK");
okBut.setActionCommand("ok");
okBut.addActionListener(this); // added this line
butPan.add(okBut, BorderLayout.SOUTH);
JButton CancelBut = new JButton("Cancel");
CancelBut.setActionCommand("Cancel");
CancelBut.addActionListener(this);
butPan.add(CancelBut, BorderLayout.SOUTH); //added this line
content.add(butPan, BorderLayout.SOUTH);
centerPan = Box.createVerticalBox();
content.add(centerPan, BorderLayout.CENTER);
pack();
show();
}
boolean isOk=false;
public void actionPerformed(ActionEvent e)
{
if ("OK".equals(e.getActionCommand()))
isOk=true;
setVisible(false);
}
}