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.