带有键 1-9 的击键不适用于 JTextComponent 的键映射



出于某些未知原因,此代码不起作用。

JTextComponent component = new JTextArea();
Keymap keymap = component.getKeymap();
keymap.addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_1, InputEvent.ALT_DOWN_MASK), myAction);

当我按Alt和1时,它从不触发myAction(不在numpad上,字母上方的1)。这也不适用于任何修饰符。

此处给出的解决方案https://stackoverflow.com/a/11974908/3838784不起作用,该操作仍然没有触发。从具有ALT作为修饰符的ALT的密钥映射中删除所有击键似乎也无济于事。

我尝试了一个示例,使用您的代码,似乎工作正常。您能告诉我是否有什么不同的代码?

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.text.JTextComponent;
import javax.swing.text.Keymap;
public class MyExample extends JFrame {
    MyExample() {
        initGUI();
    } // Constructor
    private void initGUI() {
        // Create the button
        JButton myButton = new JButton("Press ME !");
        // Create the label
        JLabel testLabel = new JLabel("TEST !!!");
        // Set up the window 
        JPanel pane = (JPanel) getContentPane();
        pane.setLayout(new BorderLayout());
        pane.add(myButton, BorderLayout.CENTER);
        pane.add(testLabel, BorderLayout.SOUTH);
        JTextComponent component = new JTextArea();
        pane.add(component, BorderLayout.SOUTH);
        Keymap keymap = component.getKeymap();
        keymap.addActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_1, InputEvent.ALT_DOWN_MASK), new MyAction());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        // setSize(600,300);  
    }
    public static void main(String[] args) {
        try {
            // Set System L&F
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        // new MyExample().setVisible(true);
        EventQueue.invokeLater(() -> {
            MyExample me = new MyExample();
            me.setVisible(true);
        });
    }
    class MyAction extends AbstractAction{
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Action performed");
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新