检查ActionPerform方法是否发生,但来自另一个类
如何检查类ModalDialog extends JDialog implements ActionListener
是否actionPerformed(ActionEvent e)
发生在另一个类(Connect extends JFrame implements ActionListener
)中的方法?还有一步,如何检查我在ModalDialog中的哪个按钮触发了ActionPerformed方法? (我知道event.getSource
,但我需要从另一个班级查看)。检查ActionPerform方法是否发生,但来自另一个类
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...
}
}
如何从一个类ModalDialog扩展的JDialog实现的ActionListener如果的actionPerformed(ActionEvent的五)
这是如何从一个类的信息返回给另一个基本问题进行检查。简单的答案是提供一个getter方法,它返回选定的值。要返回
开始通过定义的值,在这里我用了一个enum
,因为它清楚地定义了什么可以返回
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
以获取选定的值(或者如果用户通过关闭了对话框,则返回null
[X]按钮
还有一步,如何检查我在ModalDialog中有哪两个按钮触发了ActionPerformed方法?
这不是一个不常见的问题,有很多方法可以实现它。既然你已经在类一级实现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);
作为输出我总是得到机器人,无论我选择(为x我得到空)?我在ModalDialog类里面枚举了枚举,你写的我也加入了ModalDialog的ActionPerformed方法,最后一部分代码在main里。 –
对不起,在Swift中写了一个'switch'语句的不同方法,检查update – MadProgrammer
附注:你应该更好地命名你的按钮变量。 – notyou
在ActionEvent类中没有类似e.getSource()的东西吗? – deHaar