Navyah
Navyah

Reputation: 1680

Add Combobox values from listener using Swing

I am new in working with Swing. I have a requirement where I need to get data from Database and pop up in Combo box, when the combobox listener performs, it needs to load the values. I am not sure where I went wrong the values in the below code is not displaying. Can any one please correct me if I am wrong. Code:

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;

public class ComboBoxSelectionChange extends JFrame
{
    public ComboBoxSelectionChange ()
    {
        initialize();
    }

    private void initialize ()
    {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JComboBox comboBox = new JComboBox();
        comboBox.setEditable(true);
        final JTextArea textArea = new JTextArea(5, 15);
        textArea.setBorder(new BevelBorder(BevelBorder.LOWERED));

        comboBox.addItemListener(new ItemListener() {

            public void itemStateChanged (ItemEvent event)
            {
                String[] items = { "A", "B", "C", "D", "E", "F" };
                final DefaultComboBoxModel model = new DefaultComboBoxModel(
                        items);

                comboBox.setModel(model);

            }
        });

        getContentPane().add(comboBox);
        getContentPane().add(textArea);
    }

    public static void main (String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            public void run ()
            {
                new ComboBoxSelectionChange().setVisible(true);
            }
        });
    }
}

Upvotes: 0

Views: 1094

Answers (3)

splungebob
splungebob

Reputation: 5435

If I'm reading your requirements correctly, you want to wait to load the combo with a list until after they click on the drop-down arrow of the combo?

(Keep in mind, this is not a typical way of loading a combobox.)

If so, I had a similar requirement some years ago, that camickr helped me work out (back on the old Sun forums).

The idea was that user input from elsewhere on the form would drive the list of items for the combo. Deriving this list would be an expensive database query, so we didn't want to do it on every change of user input. We also didn't want a separate "Build List" button.

import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

/*
 * https://community.oracle.com/thread/2225626
 */
@SuppressWarnings("all")
public class DelayedComboBoxDemo implements Runnable
{
  private JCheckBox chkA, chkB, chkC;
  private JComboBox cboItems;
  private JFrame frame;
  
  public static void main(String[] args)
  { 
    SwingUtilities.invokeLater(new DelayedComboBoxDemo());
  }

  public void run()
  {
    chkA = new JCheckBox("A");
    chkB = new JCheckBox("B");
    chkC = new JCheckBox("C");
    
    cboItems = new JComboBox();
    cboItems.setPrototypeDisplayValue("X");
    
    JPanel p = new JPanel();
    p.add(chkA);
    p.add(chkB);
    p.add(chkC);
    p.add(cboItems);
    
    frame = new JFrame("Delayed ComboBox Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(p);
    frame.setSize(300, 100);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    cboItems.addPopupMenuListener(new PopupMenuListener()
    {
      public void popupMenuCanceled(PopupMenuEvent e) {}
      public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}

      public void popupMenuWillBecomeVisible(PopupMenuEvent e)
      {
        rebuildList();
      }
    });
  }

  private void rebuildList()
  {
    int oldCount = cboItems.getItemCount();
    
    frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    
    // simulate a long transaction
    try
    {
      Thread.sleep(200);
    }
    catch (InterruptedException ex) {}
    
    // for testing purposes, just create the list here
    Vector<String> items = new Vector<String>();
    items.add("");

    if (chkA.isSelected()) { items.add("A"); }
    if (chkB.isSelected()) { items.add("B"); }
    if (chkC.isSelected()) { items.add("C"); }

    cboItems.setModel(new DefaultComboBoxModel(items));
    
    /*
     * Workaround if using Java 5 or early Java 6. Should be fixed in 6u25.
     * See https://bugs.java.com/bugdatabase/view_bug?bug_id=4743225 
     */
    if (oldCount != cboItems.getItemCount())
    {
      cboItems.hidePopup();
      cboItems.showPopup();
    }

    frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  }
}

Upvotes: 0

SomeDude
SomeDude

Reputation: 14238

Try adding a popupmenu listener to JComboBox like :

comboBox.addPopupMenuListener( PopupMenuListener listener )
{

   protected void popupMenuWillBecomeVisible( PopupMenuEvent event )
   {
       //update your model
   }

}

Upvotes: 1

Max
Max

Reputation: 6289

You add your array to the jcombobox here comboBox.addItem(items); but then right after you reassign the jcombobox, JComboBox comboBox = (JComboBox) event.getSource();. I believe you would want to add your items after the initialization.

Add your items by using a model to hold your data.

DefaultComboBoxModel m= new DefaultComboBoxModel(items)); comboBox.setModel(m);

Upvotes: 0

Related Questions