如何设置Java默认按钮对ENTER键_released_做出反应?
2022-09-02 11:54:25
在我的应用程序中,我使用默认按钮。我希望它在释放 Key 时做出反应。按下键时不可以。ENTER
ENTER
我删除了按钮的。但它对我不起作用。我该怎么做?KeyStroke
InputMap
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class ButtonTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
buildFrame();
}
});
}
private static void buildFrame() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JButton button = new JButton(new AbstractAction("Button") {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("ButtonTest::actionPerformed: CALLED");
}
});
JButton button2 = new JButton("Button 2");
InputMap im = button.getInputMap();
im.put(KeyStroke.getKeyStroke("ENTER"), "none");
im.put(KeyStroke.getKeyStroke("released ENTER"), "released");
f.setLayout(new GridBagLayout());
f.add(button);
f.add(button2);
f.getRootPane().setDefaultButton(button);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
这是示例代码。