【发布时间】:2018-09-04 19:29:52
【问题描述】:
我有以下问题: 我的方法打开一个带有一堆按钮的 JDialog(示例代码中只有一个)。我想单击一个按钮,从而为我的方法选择一个 ImageIcon 来返回。但是该方法不会等待我单击按钮。它打开窗口,然后返回一个空的 ImageIcon。
public class Kartenauswahl {
ImageIcon bandit;
public ImageIcon auswahlfenster() {
int bwidth = new Integer(150);
int bheight = new Integer(225);
bandit = new ImageIcon("cover/Bandit.jpe");
bandit.setImage(bandit.getImage().getScaledInstance(bwidth,bheight,Image.SCALE_DEFAULT));
final JDialog kartenwahl = new JDialog();
kartenwahl.setTitle("Kartenwahl");
kartenwahl.setSize(1500,1000);
kartenwahl.setVisible(true);
kartenwahl.setLayout(new FlowLayout());
ImageIcon returnicon= new ImageIcon();
final JButton b1 = new JButton(); //just to get the Icon out of the void loop
JButton B1 = new JButton(bandit); //this is going to be the button I want to click to choose the ImageIcon which is returned
B1.setContentAreaFilled(false);
B1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
b1.setIcon(bandit);
kartenwahl.dispose();
}
});
kartenwahl.add(B1);
returnicon = (ImageIcon) b1.getIcon();
return returnicon;
}
}
问题:我可以将 return 语句绑定到条件吗?就像“只有在我点击那个按钮 B1 后才返回”?
【问题讨论】:
-
这就是你的 actionevent 的全部目的。
-
这是个问题吗?在这种情况下,答案是肯定的!
-
否则我不明白你想说什么。如果 ActionEvent 延迟返回,那我的方法为什么不起作用呢?
-
您的情况下的事件处理程序:actionPerformed。仅当用户单击事件处理程序正在访问的按钮时才会运行 (B1)。现在我看到你有第二个按钮 b1。这就是您在事件处理程序中为其设置图标的按钮。也许这是你的问题?
-
我不能直接从 EventHandler 返回 ImageIcon,因为它是一个 void 方法。所以我必须将它设置为外部 ImageIcon。由于我无法从 void 方法访问外部变量(至少这是我尝试时遇到的异常),所以我通过 Button b1.当我将 ImageIcon 发送到 b1 并因此发送“returnicon”时,该方法已经返回了空的“returnicon”。