JButton
我需要创建一个仅在按下a 时才返回的方法。我有一个自定义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
事件发生JButton
然后采取一些行动,请意识到我已经知道并且有充分的理由去做我的事情'我在这里问。请尽量只帮助我提出的问题。谢谢!!
提前:请也意识到执行 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;
}
}