Monday, June 23, 2014

6:53 PM

Good day!

A friend of mine ask me about Java swing components the JSpinner not firing on KeyListener events.

The problem is the JSpinner class supports the addKeyListener method of component, but the spinner control never calls the keyPressed, keyReleased, keyTyped of an object implementing the KeyListener interface. This was a known bug based on JSpinner editor does not fire key events unless you explicitly add JSpinner DefaultEditor cast and JTextField and using simplest form of getEditor() and getComponent() to add KeyListener interface.

Here's my solution and example code below showing a JSpinner for quantity with Double in the property model. This is very easy and slightly tricky.


I tested this code running Java 1.7

 JSpinner quantitySpinner;  
 quantitySpinner = new JSpinner();  
 quantitySpinner.setModel(new SpinnerNumberModel(new Double(0), null, null, new Double(1)));  
 quantitySpinner.getEditor().getComponent(0).addKeyListener(new KeyListener() {  
      @Override  
      public void keyTyped(KeyEvent e) {  
           // TODO Auto-generated method stub  
      }  
      @Override  
      public void keyReleased(KeyEvent e) {  
           // TODO Auto-generated method stub  
      }  
      @Override  
      public void keyPressed(KeyEvent e) {  
           System.out.println("Pressed!");  
      }  
 });  

Another solutions is to use JSpinner.DefaultEditor and with the help of JTextField, here's an example code below:

 quantitySpinner = new JSpinner();  
 quantitySpinner.setModel(new SpinnerNumberModel(new Double(0), null, null, new Double(1)));  
 Spinner.DefaultEditor editor = (JSpinner.DefaultEditor)(quantitySpinner).getEditor();  
 JTextField textField = editor.getTextField();  
 textField.addKeyListener(new KeyListener() {  
      @Override  
      public void keyTyped(KeyEvent e) {  
           // TODO Auto-generated method stub  
      }  
      @Override  
      public void keyReleased(KeyEvent e) {  
           // TODO Auto-generated method stub  
      }  
      @Override  
      public void keyPressed(KeyEvent e) {  
           System.out.prinln("Pressed");  
      }  
 });  

Take note: everytime you add KeyListener or other listeners make sure added the setModel first because it will produce logical errors without throwing Exceptions, so it might not work if you add model after assigning the KeyListener.

This also work's using FocusListener interface.

0 comments:

Post a Comment