【发布时间】:2013-01-06 21:58:18
【问题描述】:
我需要创建一个仅在按下JButton 时才返回的方法。我有一个自定义的JButton 类
public class MyButton extends JButton {
public void waitForPress() {
//returns only when user presses this button
}
}
我想实现waitForPress。基本上,该方法应该只在用户用鼠标按下按钮时返回。我为JTextField 实现了类似的行为(仅在用户按下Space 时返回):
public void waitForTriggerKey() {
final CountDownLatch latch = new CountDownLatch(1);
KeyEventDispatcher dispatcher = new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() == KeyEvent.VK_SPACE) {
System.out.println("presed!");
latch.countDown();
}
return false;
}
};
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
try {
//current thread waits here until countDown() is called (see a few lines above)
latch.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(dispatcher);
}
但我想对 JButton 做同样的事情。
提前:如果您想发表评论说这不是一个好主意,应该等待actionPerformed@987654330 上的事件@ 然后做一些动作,请意识到我已经知道了,并且有充分的理由去做我在这里要求的事情。请尽量只帮助我提出的问题。谢谢!!
提前:请注意,实施 actionPerformed 也不能直接解决问题。因为即使没有按下按钮,代码也会继续进行。我需要程序停止,并且只有在按下按钮时才返回。如果我要使用 actionPerformed,这是一个糟糕的解决方案:
public class MyButton extends JButton implements ActionPerformed {
private boolean keepGoing = true;
public MyButton(String s) {
super(s);
addActionListener(this);
}
public void waitForPress() {
while(keepGoing);
return;
}
public void actionPerformed(ActionEvent e) {
keepGoing = false;
}
}
【问题讨论】:
-
我的第一直觉告诉我你应该实现一个
ActionListener... -
您始终可以使用模态
JDialog,这是一个阻塞调用。 -
@CodeGuy:使用模态 JDialog 似乎是您想要的。然而,我强烈认为这是一个不恰当的设计,并且您当前的代码存在问题。
-
@CodeGuy 我完全意识到这里的潜在问题,并且确切地知道我在做什么 我一直在使用 UI,尤其是 Swing UI,我已经使用了一段时间,我必须说我对后一种说法表示怀疑(没有冒犯)。我看不出你怎么不能把你的代码分成两种方法,并在按下按钮时调用第二种方法。无论如何(对此感到抱歉),但如果你觉得你仍然应该追求那个想法/设计,很遗憾我帮不了你。
-
@CodeGuy 我也不想参加体验战(是的,我读了你的 Jtextfield 示例)。所以这里可能会发生两件事:1)与 EDT 不同的
Thread正在调用waitForProcess()然后,您所需要的只是调用wait()并拥有一个调用notify()的ActionListener(这只是基本的Java 线程同步)。 2)你从EDT调用waitForProcess()(然后我参考我之前的声明:将你的代码分成2个方法并在actionPerformed()中调用第二个)
标签: java swing jbutton jtextfield