如何从类(class)检查ModalDialog extends JDialog implements ActionListener
如果actionPerformed(ActionEvent e)
方法发生在另一个类中( Connect extends JFrame implements ActionListener
)?更进一步,如何检查 ModalDialog 中的两个按钮中哪一个触发了 ActionPerformed 方法? (我知道 event.getSource
,但我需要从另一个类(class)检查它)。
public ModalDialog()
{
btn8 = new Button("human");
btn8.setMaximumSize(new Dimension(60,40));
btn8.addActionListener(this);
btn9 = new Button("robot");
btn9.setMaximumSize(new Dimension(60,40));
btn9.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
}
class Connect extends JFrame implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
ModalDialog md = new ModalDialog();
if(md.ActionPerformed(e)....)...something like that...
}
}
最佳答案
How to check from a class ModalDialog extends JDialog implements ActionListener if actionPerformed(ActionEvent e)
这是如何将信息从一个类返回到另一个类的基本问题。简单的答案是提供一个 getter 方法,该方法返回选定的值。
首先定义要返回的值,这里我使用了枚举
,因为它清楚地定义了可以返回的内容
public enum Option {
HUMAN, ROBOT;
}
更新您的ModalDialog
以提供一个getter来返回所选值
public class ModalDialog extends JDialog implements ActionListener {
private Option selection;
public ModalDialog() {
setModal(true);
Button btn8 = new Button("human");
btn8.addActionListener(this);
Button btn9 = new Button("robot");
btn9.addActionListener(this);
setLayout(new GridBagLayout());
add(btn8);
add(btn9);
pack();
}
public Option getSelection() {
return selection;
}
public void actionPerformed(ActionEvent e) {
//...
}
}
当对话框关闭时,调用者现在可以调用 getSelection
来获取所选值(如果用户通过 [X ]按钮
And one step further, how to check which of two buttons that I have in ModalDialog fired ActionPerformed method?
这并不是一个罕见的问题,您可以通过多种方式来实现它。由于您已经在类级别实现了 ActionListener
,因此您可以利用按钮中提供的 actionCommand
支持,该支持默认为按钮的文本
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
switch (cmd) {
case "human":
selection = Option.HUMAN;
break;
case "robot":
selection = Option.ROBOT;
break;
}
setVisible(false);
}
现在,当对话框关闭时,您可以只请求选定的值...
ModalDialog dialog = new ModalDialog();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
Option selection = dialog.getSelection();
System.out.println("You choose " + selection);
关于java - 检查 ActionPerformed 方法是否发生但来自另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46749117/