This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

itemlistener gets event after focus is removed from jcombobox

By: a guest on Feb 22nd, 2012  |  syntax: None  |  size: 1.81 KB  |  views: 6  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. //Code from Netbeans generator
  2. JComboBox myCbx = new javax.swing.JComboBox();    
  3. myCbx.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
  4. myCbx.setName("myCbx"); // NOI18N
  5. //My ItemListener
  6. class myItemListener implements ItemListener{
  7. public void itemStateChanged(ItemEvent ie) {
  8.             if (ie.getStateChange() == ItemEvent.SELECTED) { // Item was just selected
  9.                 updateJTextPane();
  10.             }    
  11.          }
  12.     }
  13. //add item listener to combo
  14. myCbx.addItemListener(new myItemListener());
  15.        
  16. class Frame extends JFrame {
  17.     JComboBox  box;
  18.     JTextField field;
  19.     String[]   entries = { "one", "two", "three" };
  20.  
  21.     Frame() {
  22.         setLayout(new FlowLayout());
  23.  
  24.         box = new JComboBox(entries);
  25.         box.addItemListener(new ItemListener() {
  26.             @Override
  27.             public void itemStateChanged(ItemEvent e) {
  28.                 if (e.getStateChange() == ItemEvent.SELECTED) {
  29.                     field.setText((String) box.getSelectedItem());
  30.                 }
  31.             }
  32.         });
  33.         add(box);
  34.  
  35.         field = new JTextField();
  36.         field.setColumns(10);
  37.         add(field);
  38.  
  39.         setSize(400, 300);
  40.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  41.         setVisible(true);
  42.     }
  43. }
  44.  
  45. public class Test {
  46.  
  47.     public static void main(String[] args) {
  48.         SwingUtilities.invokeLater(new Runnable() {
  49.             public void run() {
  50.                 Frame frame = new Frame();
  51.             }
  52.         });
  53.  
  54.     }
  55. }
  56.        
  57. class ComboListener implements ItemListener {
  58.     @Override
  59.     public void itemStateChanged(ItemEvent e) {
  60.         if (e.getStateChange() == ItemEvent.SELECTED) {
  61.             System.out.println("Selected Item: ""
  62.                 + ((JComboBox)e.getSource()).getSelectedItem() + """);
  63.         }
  64.     }
  65. }
clone this paste RAW Paste Data