我正在处理一项必须使用 AWT 完成的 Java 作业。我希望在按钮处于焦点状态时通过按回车键来触发按钮。我想出了如何使用 doClick() 方法在 Swing 中执行此操作,但这似乎在 AWT 中不起作用。到目前为止,我正在尝试这个:
button.addActionListener(this); // Passes value from a TextBox to actionPerformed()
button.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER) {
actionPerformed(null);
}
}
});
public void actionPerformed (ActionEvent e) {
try {
if (e.getSource() == button) {
// Stuff I want to happen
} else if (e.getSource() == anotherButton) {
// Other Stuff
} else { //third button
// More stuff
}
} catch (NumberFormatException nfe) {
// Null argument in keyPressed triggers this
// catches empty string exception from TextBox
}
}
正如我在评论中提到的,null 参数将触发捕获。有谁知道按钮按下的论点是什么,或者可能是一种更简单的方法来解决这个问题?谢谢。
编辑 - 说明:actionPerformed() 根据单击三个按钮中的哪一个,对来自 TextBox 的输入执行三项操作之一。 try/catch 用于捕获空字符串/格式异常。
最佳答案
您始终可以拥有一个名为 onButtonPress()
的方法,您的 actionPerformed
以及您的 keyPressed
都可以调用它。
button.addActionListener(this);
button.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
onButtonPress();
}
}
});
public void actionPerformed (ActionEvent e) {
if (e.getSource() == button){
onButtonPress();
}
}
private void onButtonPress(){
// do something
}
关于java - 将按钮点击事件传递给 actionPerformed on key press,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9013034/