6

I'm looking to create a JComboBox that acts as a menu. For example, when you drop it down, you can select items like you would in a JMenuBar.

So it would take JMenus and JMenuItems as instead of Strings.

Is this possible?

jzd
  • 23,473
  • 9
  • 54
  • 76
user489041
  • 27,916
  • 55
  • 135
  • 204
  • 1
    That is the way a JCombobox works. You click on an item to select it. You can add an ActionListener to the combo box to do so processing based on the item selected. I don't see the reason for confusing the user by trying to mix the functionality of a menu and a combo box. – camickr Mar 14 '11 at 18:15
  • I dont see any difference between JMenu and JCombobox because both uses JPopupMenu. JMenu acts as JCombobox what is the need of JCombobox? – Umesh K Mar 14 '11 at 18:16
  • I want it to be able to have submenus. So instead of just dropping a list, it drops a list of menus, you can then go into that menu. I would like it to be consistent with the other components of my GUI. I didnt want to have a random menu in there – user489041 Mar 14 '11 at 18:16

2 Answers2

2

One way to accomplish this would be to create a button that when clicked shows a JPopupmenu, just below the button. The menu would allow the user to select from the menu or submenu. The label/selection of the original button should be changed when a menu item is selected.

jzd
  • 23,473
  • 9
  • 54
  • 76
-1

Is this you are looking for??

  //package combo2;

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

  public class Combo2 implements ItemListener {

JFrame f1;
JComboBox c;
JPanel p ;

JLabel j;
Combo2()
{
JFrame f1 = new JFrame("Selection");
            Container f = new Container();
            f.setLayout(new FlowLayout());

            String s [] = {"Red","Green","Yellow","Black"};
            c = new JComboBox(s);
            j = new JLabel();
             p= new JPanel();

            c.addItemListener(this);

            f1.add(p);
            p.add(c);
            p.add(j);

            f1.setSize(500,500);
            f1.setVisible(true);

            }
            public void itemStateChanged(ItemEvent ie)
            {
            String str = (String)c.getSelectedItem();
            j.setText(str);
            }
                public static void main(String[] args) {
                    Combo2 l = new Combo2();
                }
            }
Zameer Ansari
  • 28,977
  • 24
  • 140
  • 219