Multiple Keys in KeyEvent Listener

血红的双手。 提交于 2019-12-25 02:44:07

问题


I was wondering how to get all of the keys pressed in a key event. For example, I want to write a listener for ctrl + f that would toggle fullscreen. How could I check if both ctrl and f are pressed in one event?


EDIT 1:

I tried printing KeyEvent.getModifiersExText(e.getModifiersEx()) and typing ctrl + f, but that just yielded ?.


回答1:


To be honest, KeyListener has many limitations and is cumbersome to use (IMHO), instead, I would simply take advantage of the key bindings API, which generally provides you with a greater deal of flexibility and potentional for resuse.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class KeyListenerTest {

    public static void main(String[] args) {
        new KeyListenerTest();
    }

    public KeyListenerTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel lbl;
        private boolean fullScreen = false;

        public TestPane() {
            lbl = new JLabel("Normal");
            setLayout(new GridBagLayout());
            add(lbl);

            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK), "FullScreen");
            am.put("FullScreen", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (fullScreen) {
                        lbl.setText("Normal");
                    } else {
                        lbl.setText("Full Screen");
                    }
                    fullScreen = !fullScreen;
                }
            });

        }

    }

}

And just so you don't think I'm completely bias, here's an example using KeyListener...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class KeyListenerTest {

    public static void main(String[] args) {
        new KeyListenerTest();
    }

    public KeyListenerTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel lbl;
        private boolean fullScreen = false;

        public TestPane() {
            lbl = new JLabel("Normal");
            setLayout(new GridBagLayout());
            add(lbl);

            setFocusable(true);
            addMouseListener(new MouseAdapter() {

                @Override
                public void mouseClicked(MouseEvent e) {
                    requestFocusInWindow();
                }

            });

            addKeyListener(new KeyAdapter() {

                @Override
                public void keyPressed(KeyEvent e) {
                    if (e.getKeyCode() == KeyEvent.VK_F && e.isControlDown()) {
                        if (fullScreen) {
                            lbl.setText("Normal");
                        } else {
                            lbl.setText("Full Screen");
                        }
                        fullScreen = !fullScreen;
                    }
                }

            });
        }
    }
}



回答2:


Something like this should do it:

public MyListener extends KeyListener {
    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if ((e.getKeyCode() == KeyEvent.VK_F) && ((e.getModifiers() & KeyEvent.CTRL_DOWN_MASK) != 0)) {
            System.out.println("Keys ctrl+F pressed!");
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
});



回答3:


I found a few cool methods that will work in this instance:

e.isAltDown();

e.isAltGraphDown()

e.isControlDown()

e.isShiftDown()




回答4:


If you press two keys the 'keyPressed(KeyEvent e)' is called twice. You can store the pressed key in a boolean array and check if they are both pressed.

private boolean control_pressed = false;

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
      control_pressed = true;
    }

    if (e.getKeyCode() == KeyEvent.VK_F && control_pressed) {
        /* do something */
    }
}

public void keyReleased(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
      control_pressed = false;
    }
}

The release has to release the control variable again.



来源:https://stackoverflow.com/questions/19823633/multiple-keys-in-keyevent-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!