如何设置Java默认按钮以对ENTER键_released_作出反应?

Hir*_*tha 15 java swing defaultbutton event-handling

在我的应用程序中,我使用默认按钮.我希望它在ENTERKey 发布时作出反应.不是当ENTER是关键按下.

我删除了KeyStrokeInputMap按钮的.但它对我不起作用.我该怎么做?


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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是示例代码.

小智 28

JRootPane rootPane = SwingUtilities.getRootPane(/* Your JButton  */); 
rootPane.setDefaultButton(/* Your JButton  */);
Run Code Online (Sandbox Code Playgroud)

  • 你的代码给我NPE,而这是有效的 - "JRootPane rootPane = SwingUtilities.getRootPane(/*你的JFrame*/); ` (2认同)
  • @raghavsood33 `SwingUtilities.getRootPane(yourJButton);` 只有在调用了 `yourJFrame.add(yourJButton)` 的效果后才可以在没有 NPE 的情况下工作。在将按钮添加到框架(或已添加到框架的容器)之前,按钮显然不会有根窗格。 (2认同)

kle*_*tra 7

默认按钮的键(即,在输入时触发的按钮,无论是哪个组件是focusOwner)都绑定在rootPane的componentInputMap中,即它的WHEN_IN_FOCUSED_WINDOW类型的inputMap.从技术上讲,这是调整的地方:

JComponent content = new JPanel();
content.add(new JTextField("some focusable"));
content.add(new JTextField("something else"));

JXFrame frame = wrapInFrame(content, "default button on released");
Action action = new AbstractAction("do something") {

    @Override
    public void actionPerformed(ActionEvent e) {
        LOG.info("clicked");
    }
};
JButton button = new JButton(action);
content.add(button);
frame.getRootPane().setDefaultButton(button);
// remove 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");
Run Code Online (Sandbox Code Playgroud)

注意:这仍然与非默认按钮的按下/释放行为不同,因为rootPane操作只是调用按钮.单击而不经过布防/按下buttonModel的移动以间接触发操作.