How to make an event by pressing two keys?

0

I'm doing a program where I want to include keyboard shortcuts. The program in question has a series of jTextFields that I want to fill directly with the keyboard without having to be jumping from field to field, and I also want to be able to do it so that I increase the values by 1 each time.

For example, if I press Q + 1, a jtextfield will increase its value by 1 point, if I press e + 2, another jtextfield will increase by one point (the keys I have set are examples).

Neither do I know where I should put the event.

    
asked by Carlos Gargallo 15.10.2017 в 14:10
source

1 answer

1

Good morning,

Here I give you an example of a textfield that only allows numbers and with two keyboard shortcuts:

    // Numeros enteros como formato
    NumberFormat format = NumberFormat.getIntegerInstance();
    NumberFormatter formatter = new NumberFormatter(format);
    formatter.setValueClass(Integer.class);
    formatter.setAllowsInvalid(false);

    // Textfield iniciado a 0 y alineado a la derecha
    JFormattedTextField textField = new JFormattedTextField(formatter);
    textField.setValue(0);
    textField.setHorizontalAlignment(JTextField.RIGHT);

    // Atajos de teclado
    textField.addKeyListener(new KeyAdapter() {         
        @Override
        public void keyPressed(KeyEvent e) {
            // Para sumar uno
            if ((e.getKeyCode() == KeyEvent.VK_Q) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
                textField.setValue(((Integer.valueOf(textField.getText()) + 1)));

            // Para restar uno
            } else if((e.getKeyCode() == KeyEvent.VK_A) && ((e.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
                textField.setValue(((Integer.valueOf(textField.getText()) - 1)));
            }           
        }
    });

    // Ventana que lo contiene
    JFrame frame = new JFrame();
    frame.getContentPane().add(textField);      
    frame.pack();
    frame.setVisible(true);

The first thing is to create the format so that it only allows entering whole numbers.

Once we create the textfield with the configuration we want. We add the listeners for when they press a key.

You were talking about Q + 1 or Q - 1 but normally in the keyboard shortcuts a modifier is used, such as ctrl or shift and a key. In the example I used ctrl to add and ctrl to subtract.

I hope I have helped you.

Greetings.

    
answered by 15.10.2017 / 20:51
source