How to determine the "Alt +" click, correctly and reliably?

My question is actually more general, but I am using the action of the user holding the "Alt" key and pressing the "+" as an example that shows difficulties.

I work on an English English keyboard with "=" (lowercase letters) and "+" (uppercase) on the same key, so press "Alt +" (as may be indicated in the menu entry), I should on actually press "Alt Shift =". In Java AWT, pressing the Alt Shift = key generates a KeyEvent key press with the key code associated with the = key and the KeyDisc KeyEvent with a ± symbol. Thus, there is no obvious and reliable way to programmatically decide that "Alt" is held down by the "+" key.

I could do some mapping inside to fix this, for example, matching "±" with "Alt +" or mapping "Shift {keycode for =}" to "+". However, there seems to be no guarantee that this will work in different keyboard layouts; and this, of course, is not a very good coding style.

If anyone can suggest a way around these issues, or perhaps point to code that has already dealt with this difficulty, I would be very grateful.

Thanks.

+4
source share
1 answer

Try the following:

if(e.isAltDown()) { switch(e.getKeyChar()) { case '+': System.out.println("Plus"); break; } } 

Where e is a KeyEvent and is processed in the keyPressed method.

The code above will print Plus when you press ALT + Shift + = on your keyboard.

Full working code is given below:

 import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; import javax.swing.UIManager; public class SwingTest { private static JFrame frame; public static void main(String[] args) throws Exception { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception ex) { ex.printStackTrace(); } } frame = new JFrame("Event Test"); Toolkit tk = Toolkit.getDefaultToolkit(); int xSize = ((int) tk.getScreenSize().getWidth()/2) + 100; int ySize = ((int) tk.getScreenSize().getHeight()/2) + 50; frame.setSize(xSize,ySize); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void keyPressed(KeyEvent e) { if(e.isAltDown()) { switch(e.getKeyChar()) { case '+': System.out.println("Plus"); break; } } } }); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { frame.setVisible(true); } }); } } 

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1345456/


All Articles