mca*_*der 1 java awt keyevent keylistener actionlistener
我正在进行必须使用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
}
}
Run Code Online (Sandbox Code Playgroud)
正如我在评论中提到的那样,null参数将触发catch.有没有人知道按钮按下可能是什么参数或者可能是一个更简单的方法来解决这个问题?谢谢.
编辑 - 澄清: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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19670 次 |
| 最近记录: |