1

it's really simple. I want to populate a jcomboBox but only after the user press the arrow on the combobox.

I think the code is right cause i test it in a separate button and it populate the Combobox but when i create an action listener for the combobox itself it doesn't populate, Here are the code.

comboBox.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            comboBox.addItem("Item");
            comboBox.addItem("Second Item");

        }

It's a country city neighborhood situation . What i want is the second to be populated when the first is selected .

The first box is easy to populate (The country box) But the second box (City) I added a switch for it but it just won't populate , What i want to know is there an action i should put my code into for it to populate ?

random-xyz
  • 137
  • 4
  • 14

3 Answers3

3

I want to populate a jcomboBox but only after the user press the arrow on the combobox.

Why would the user look at an empty combo box and then click on the arrow? If the contents of the combo box are based on some other user Action, then that Action should cause the combo box to be populated.

Anyway, maybe you are trying to popuplate the combo box when the dropdown is displayed?

That is the user could click anywhere on the combo box, not just the down arrow.

In this case you can use a PopupMenuListener

comboBox.addPopupMenuListener(new PopupMenuListener()
{
    public void popupMenuWillBecomeVisible(PopupMenuEvent e)
    {
        JComboBox comboBox = (JComboBox)e.getSource();
        comboBox.addItem("Item1");
        comboBox.addItem("Item2");
        comboBox.addItem("Item3");
        comboBox.addItem("Item4");
    }

    public void popupMenuCanceled(PopupMenuEvent e) {}
    public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
});

Edit:

It's a country city neighborhood situation .

Which is a requirement that should have been included with your original question. As people has suggested your approach is wrong. The child combo boxes should be updated when the parent is changed, not when you click the child.

See How to Update Multiple Combo Boxes for a better solution. The example there only shows 2 combo boxes, but the concept is the same for the second and third.

Community
  • 1
  • 1
camickr
  • 321,443
  • 19
  • 166
  • 288
  • Thank you so much that worked, problem is , it just keeps on adding on each click. It's a country city neighborhood situation . What i want is the second to be populated when the first is selected but empty until pressed down . – random-xyz Jul 06 '15 at 04:01
  • The first box is easy to populate (The country box) But the second box (City) I added a switch for it but it just won't populate , What i want to know is there an action i should put my code into for it to populate ?Thank you again all . – random-xyz Jul 06 '15 at 04:16
  • `it just keeps on adding on each click` - well the code was an example not a complete solution. You can easily check the item count and only add items when the count is 0. However, this is not the best solution. I edited the answer for a better solution that contains a working example. – camickr Jul 07 '15 at 15:18
2

Pressing a JComboBox arrow doesn't trigger the ActionListener. Only making a selection does, and so your combo box will need to be populated before the arrow has been pressed. You'll have to re-think your design such as populating the combo box before the user interacts with it.

If you absolutely needed to add an action listener to the arrow button, it can be done, such as via a recursive method:

import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.*;

public class Foo extends JPanel {
   private JComboBox<String> combo = new JComboBox<>();

   public Foo() {
      add(combo);

      combo.addMouseListener(new MouseAdapter() {
         @Override
         public void mousePressed(MouseEvent e) {
            // this doesn't work!!!
            System.out.println("mouse pressed");
            super.mousePressed(e);
         }
      });
      recursiveAddAxnListener(combo);
   }

   private void recursiveAddAxnListener(Component comp) {
      if (comp instanceof AbstractButton) {
         ((AbstractButton) comp).addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent evt) {
               System.out.println("added to combo's button");
            }
         });
      } else if (comp instanceof Container) {
         Component[] comps = ((Container) comp).getComponents();
         for (Component component : comps) {
            recursiveAddAxnListener(component);
         }
      }
   }

   private static void createAndShowGUI() {
      Foo paintEg = new Foo();

      JFrame frame = new JFrame("Foo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(paintEg);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

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

But do I recommend it? No, not at all.


Edit
You have edited your question and have added:

It's a country city neighborhood situation . What i want is the second to be populated when the first is selected .
The first box is easy to populate (The country box) But the second box (City) I added a switch for it but it just won't populate , What i want to know is there an action i should put my code into for it to populate ?

You may be asking an XY-Problem type question where you ask how do I solve X code problem when the best solution is to use an entirely different approach. In this situation I strongly recommend that you not populate the second combobox on mouse press, but rather populate it only once and do it when the first combobox selection has been made. In other words, populate the 2nd combo box in the first combo box's ActionListener. This will simplify things greatly and prevent re-population of the 2nd combobox unnecessarily.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Thank you for that i'm trying to do that populate the second box when the first is selected, but problem is each time i select a county in the first box it keeps adding to the second box (city). Even though i added combobox.removeall(); in switch in the beginning in each case.for example if i choose usa once and my condition is to add california in the second box if that's selected, It does that but when i choose France for example second time i can see california and Paris in the second box. – random-xyz Jul 06 '15 at 21:23
  • @user3195313: then you've got a bug in code not shown. You will want to consider creating and posting an [sscce](http://sscce.org) or a [minimal example program/mcve](http://stackoverflow.com/help/mcve) where you condense your code into the smallest bit that still compiles and runs, has no outside dependencies (such as need to link to a database or images), has no extra code that's not relevant to your problem, but still demonstrates your problem. – Hovercraft Full Of Eels Jul 06 '15 at 22:31
0

Thank you all for your help , you have been just awesome.

I found the problem I had to have the combobox.removeallItems(); before the switch not in the switch.

This is the testing version of it.and it worked.

JComboBox comboBox = new JComboBox();
    comboBox.addItem("");
    comboBox.addItem("first");
    comboBox.addItem("second");
    comboBox.addItem("third");

    comboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            comboBox_1.removeAllItems();

            String test = comboBox.getSelectedItem().toString();

            switch (test) {
            case "first":


                comboBox_1.addItem("Tesing");

                break;
            case "second":

                comboBox_1.addItem("Tesing2");

                break;
            case "third":

                comboBox_1.addItem("Tesing three");

                break;

            default:
                break;
            }

        }
    });

Again , i appreciate all the help , Thank you so much.

random-xyz
  • 137
  • 4
  • 14