我有一个包含许多行文本字段和提交按钮的JDialog。我想知道是否可以将eventListener添加到容器中以触发提交按钮。
答案 0 :(得分:2)
尝试添加
frame.getRootPane().setDefaultButton(button);
// removing the binding for pressed
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke("ENTER"), "none");
// retarget the binding for released
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke("released ENTER"), "press");
或者执行以下
之类的操作 addKeyListener(new KeyListener(){
@Override
public void keyPressed(KeyEvent ke)
{
if (e.getKeyCode().equals(KeyEvent.VK_ENTER))
{
//copy paste the logic you wrote inside the ActionPerformed method
}
}});
setFocusable(true);//Setting Focus true for ur container
requestFocusInWindow();//Requesting the focus. Without this, KeyEvent will not trigger on your container
答案 1 :(得分:2)
将 Enter 绑定到Action
的一种便捷方法是通过根窗格的setDefaultButton()
方法。您还可以使用key binding中的Action
,如图所示here。
JDialog d = new JDialog(…);
Action submit = new AbstractAction("Submit") {
@Override
public void actionPerformed(ActionEvent e) {
// handle submit
}
};
private JButton b = new JButton(submit);
…
d.getRootPane().setDefaultButton(b);