Advertisement
Guest User

Behavior of a JComboBox in a JTable - Fix

a guest
May 3rd, 2012
720
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.98 KB | None | 0 0
  1. import java.awt.event.KeyEvent;
  2. import java.awt.event.KeyListener;
  3.  
  4. import javax.swing.JComboBox;
  5. import javax.swing.JList;
  6. import javax.swing.JTextField;
  7. import javax.swing.plaf.basic.ComboPopup;
  8.  
  9. /**
  10.  * This is a quick fix to change the behavior of a JComboBox in a JTable.
  11.  *
  12.  * In a normal editable JComboBox the user is able to select entries with the arrow keys.
  13.  * On each change the value of the JTextField (editorComponent) changes as well and you can
  14.  * leave the ComboBox with TAB.
  15.  *
  16.  * In a JTable this described behavior changes. The value of the JTextField does not change
  17.  * when a different value in the list gets selected. So the user is forced to press the
  18.  * enter key in order to save the value.
  19.  *
  20.  * This ClientProperty triggers this change.
  21.  * combobox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
  22.  *
  23.  * I can give no warranty that this will work in every case. But for me it simply did it.
  24.  *
  25.  * If you have any suggestions please write me a mail to wolfgang.jentner[at]sfg-singen.de
  26.  *
  27.  * @author Wolfgang Jentner
  28.  *
  29.  */
  30. public class ComboBoxTableFix {
  31.     /**
  32.      * This is a decorator method. Simply put your JComboBox in.
  33.      *
  34.      * @param combobox - An editable JComboBox.
  35.      */
  36.     public static void fix(JComboBox combobox) {
  37.         if(!combobox.isEditable()) return;
  38.        
  39.         final JList c_list = ((ComboPopup) combobox.getUI().getAccessibleChild(combobox, 0)).getList();
  40.         final JTextField c_field = (JTextField) combobox.getEditor().getEditorComponent();
  41.        
  42.         c_field.addKeyListener(new KeyListener() {
  43.            
  44.             @Override
  45.             public void keyTyped(KeyEvent e) {}
  46.            
  47.             @Override
  48.             public void keyReleased(KeyEvent e) {
  49.                 if(e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_UP) {
  50.                     Object val = c_list.getSelectedValue();
  51.                     if(val != null) {
  52.                         c_field.setText(String.valueOf(val));
  53.                     }
  54.                     c_field.selectAll();
  55.                 }
  56.             }
  57.            
  58.             @Override
  59.             public void keyPressed(KeyEvent e) {}
  60.         });
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement