什么是Java中表示“>”的合适按键事件?

huangapple go评论142阅读模式
英文:

What is the proper Key Event for '>' in Java?

问题

以下是翻译好的内容:

我在一个项目中被告知要特别区分按键 .,< 以及 >。我看到了一个名为 KeyEvent.VK_GREATERKeyEvent.VK_LESS 的 KeyEvent,但当我通过打印字符串进行测试时,什么都没有发生。

请帮帮我 什么是Java中表示“>”的合适按键事件?

public void keyPressed(KeyEvent e)
{
    boolean b = Utilities.isShiftDown(e);

    switch (e.getKeyCode())
    {
        case KeyEvent.VK_Q:
            System.exit(0);
            break;
        case KeyEvent.VK_LESS:
            System.out.println("I'm Left");
            break;
    }
}
}
英文:

I was told in a project to especially differentiate keypresses between . and , from < and >. I saw a KeyEvent called KeyEvent.VK_GREATER and KeyEvent.VK_LESS but when I test it out through printing a string, nothing happens.

Please help 什么是Java中表示“>”的合适按键事件?

public void	keyPressed(KeyEvent e)
	{
		boolean	b = Utilities.isShiftDown(e);

		switch (e.getKeyCode())
		{
			case KeyEvent.VK_Q:
				System.exit(0);
				break;
			case KeyEvent.VK_LESS:
				System.out.println("I'm Left");
				break;
		}
	}
}

答案1

得分: 2

代码部分不提供翻译,如下所示:

Sure it works for `<` and `>`

import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class KeyListenerTest extends JPanel {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Foo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new KeyListenerTest());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }

    public KeyListenerTest() {
        setPreferredSize(new Dimension(400, 300));
        setFocusable(true);
        requestFocusInWindow();
        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                super.keyPressed(e);
                System.out.printf("Key id: %d; Key char: %c; key code: %d; Modifiers ex: %d%n",
                        e.getID(), e.getKeyChar(), e.getKeyCode(), e.getModifiersEx());
            }
        });
    }
}

those keys return

Key id: 401; Key char: <; key code: 44; Modifiers ex: 64
Key id: 401; Key char: >; key code: 46; Modifiers ex: 64

These are the same key codes as common and period but with a non-0 modifiers ex of 64, consistent with the `SHIFT_DOWN_MASK` value for the modifierex, indicating that the shift key is pressed.

And to specifically test for greater than and less than, you'd check both key code and modifiers ex:

if (e.getKeyCode() == KeyEvent.VK_COMMA && (e.getModifiersEx() & KeyEvent.SHIFT_DOWN_MASK) != 0) {
    System.out.println("LESS-THAN pressed");
}
if (e.getKeyCode() == KeyEvent.VK_PERIOD && (e.getModifiersEx() & KeyEvent.SHIFT_DOWN_MASK) != 0) {
    System.out.println("GREATER-THAN pressed");
}

_______________________________________________________

Key Bindings version of program:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class KeyBindingTest extends JPanel {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Foo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new KeyBindingTest());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }

    public KeyBindingTest() {
        setPreferredSize(new Dimension(400, 300));

        KeyStroke lessThanKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, KeyEvent.SHIFT_DOWN_MASK);
        KeyStroke greaterThanKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, KeyEvent.SHIFT_DOWN_MASK);

        int condition = WHEN_IN_FOCUSED_WINDOW;
        InputMap inputMap = getInputMap(condition);
        ActionMap actionMap = getActionMap();

        borderFlash(lessThanKeyStroke, inputMap, actionMap, Color.BLUE);
        borderFlash(greaterThanKeyStroke, inputMap, actionMap, Color.RED);
    }

    private void borderFlash(KeyStroke ks, InputMap inputMap, ActionMap actionMap, Color color) {
        KeyStroke press = KeyStroke.getKeyStroke(ks.getKeyCode(), ks.getModifiers(), false);
        KeyStroke release = KeyStroke.getKeyStroke(ks.getKeyCode(), ks.getModifiers(), true);

        inputMap.put(press, press.toString());
        inputMap.put(release, release.toString());

        actionMap.put(press.toString(), new BorderFlashAction(color, false));
        actionMap.put(release.toString(), new BorderFlashAction(color, true));
    }

    private class BorderFlashAction extends AbstractAction {
        private static final int THICKNESS = 20;
        private Color color;
        private boolean release;

        public BorderFlashAction(Color color, boolean release) {
            this.color = color;
            this.release = release;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (release) {
                setBorder(null);
            } else {
                setBorder(BorderFactory.createLineBorder(color, THICKNESS));
            }
        }
    }
}
英文:

Sure it works for &lt; and &gt;

import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class KeyListenerTest extends JPanel {
public static void main(String[] args) {
SwingUtilities.invokeLater(()-&gt; {
JFrame frame = new JFrame(&quot;Foo&quot;);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new KeyListenerTest());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
public KeyListenerTest() {
setPreferredSize(new Dimension(400, 300));
setFocusable(true);
requestFocusInWindow();
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
System.out.printf(&quot;Key id: %d; Key char: %c; key code: %d; Modifiers ex: %d%n&quot;, 
e.getID(), e.getKeyChar(), e.getKeyCode(), e.getModifiersEx());
}
});
}
}

those keys return

Key id: 401; Key char: &lt;; key code: 44; Modifiers ex: 64
Key id: 401; Key char: &gt;; key code: 46; Modifiers ex: 64

These are the same key codes as common and period but with a non-0 modifiers ex of 64, consistent with the SHIFT_DOWN_MASK value for the modifierex, indicating that the shift key is pressed.

And to specifically test for greater than and less than, you'd check both key code and modifiers ex:

if (e.getKeyCode() == KeyEvent.VK_COMMA &amp;&amp; (e.getModifiersEx() &amp; KeyEvent.SHIFT_DOWN_MASK) != 0) {
System.out.println(&quot;LESS-THAN pressed&quot;);
}
if (e.getKeyCode() == KeyEvent.VK_PERIOD &amp;&amp; (e.getModifiersEx() &amp; KeyEvent.SHIFT_DOWN_MASK) != 0) {
System.out.println(&quot;GREATER-THAN pressed&quot;);
}

Key Bindings version of program:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
@SuppressWarnings(&quot;serial&quot;)
public class KeyBindingTest extends JPanel {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -&gt; {
JFrame frame = new JFrame(&quot;Foo&quot;);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new KeyBindingTest());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
public KeyBindingTest() {
setPreferredSize(new Dimension(400, 300));
KeyStroke lessThanKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, KeyEvent.SHIFT_DOWN_MASK);
KeyStroke greaterThanKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, KeyEvent.SHIFT_DOWN_MASK);
int condition = WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = getInputMap(condition);
ActionMap actionMap = getActionMap();
borderFlash(lessThanKeyStroke, inputMap, actionMap, Color.BLUE);
borderFlash(greaterThanKeyStroke, inputMap, actionMap, Color.RED);
}
private void borderFlash(KeyStroke ks, InputMap inputMap, ActionMap actionMap, Color color) {
KeyStroke press = KeyStroke.getKeyStroke(ks.getKeyCode(), ks.getModifiers(), false);
KeyStroke release = KeyStroke.getKeyStroke(ks.getKeyCode(), ks.getModifiers(), true);
inputMap.put(press, press.toString());
inputMap.put(release, release.toString());
actionMap.put(press.toString(), new BorderFlashAction(color, false));
actionMap.put(release.toString(), new BorderFlashAction(color, true));
}
private class BorderFlashAction extends AbstractAction {
private static final int THICKNESS = 20;
private Color color;
private boolean release;
public BorderFlashAction(Color color, boolean release) {
this.color = color;
this.release = release;
}
@Override
public void actionPerformed(ActionEvent e) {
if (release) {
setBorder(null);
} else {
setBorder(BorderFactory.createLineBorder(color, THICKNESS));
}
}
}
}

答案2

得分: 0

也许对于一些简单的操作,可以使用 KeyEvent#getKeyChar() 方法,像这样:

if (e.isShiftDown()) {
    switch (e.getKeyChar()) {
        case 'Q':
            System.out.println("退出!");
            System.exit(0);
            break;
        case '<':
            System.out.println("我在左边");
            break;
    }
}
英文:

Well for something simple maybe use the KeyEvent#getKeyChar() method instead, like this:

if (e.isShiftDown()) {
switch (e.getKeyChar()) {
case &#39;Q&#39;:
System.out.println(&quot;EXITING!&quot;);
System.exit(0);
break;
case &#39;&lt;&#39;:
System.out.println(&quot;I&#39;m Left&quot;);
break;
}
}

huangapple
  • 本文由 发表于 2020年4月7日 09:26:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/61071408.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定