JCheckBoxMenuItem in a  JComboBox

How do we add a JCheckBoxMenuItem to a JComboBox

I am putting CheckBoxMenuItems in a combox as I am simulating a scrollable popup menu using a combo box.

Similar Messages

  • Adding an array of objects to a JComboBox

    Hi hope someone can help I have searched the forums and cannot find any previous questions that cover this.
    Basically I want to construct a JComboBox and instead of populating the ComboBox with strings Im wanting to add check boxes.
    First Question can this actually be done?
    Second Question how?
    I have included a sample of the code to show what i mean.
    JCheckBox[] layerChecks = new JCheckBox[numberLayers];
    for(int i =0; i<numberLayers; i++)
    layerChecks[i] = new JCheckBox();
    layerChecks.setText(nameLayers[i]);
    JComboBox layersComboBox = new javax.swing.JComboBox(layerChecks);
    add(layersComboBox);
    Any help is much appreciated.

    Whenever something like this crops up, you should do a double check
    to see of what you are trying to do makes sense.
    I'm not saying it doesn't, but from a user point of view, a combo box
    with checkboxes is something a user hasn't seen before, so they might not like it.
    I've recently done some combo box stuff. What I did was:
    subclass MetalComboBoxUI (and WindowsComboBoxUI and MotifComboBoxUI).
    In the createPopup() method of the UI create a BasicComboPopup (or MotifCalendarPopup). The BasicComboPopup is a subclass of JPopupMenu, that uses a JList so you do a popup.removeAll() to get rid of the list, then add your item(s) to the popup.
    ...works for me !
    infact here is the basic structure. You'll need to modify to make it
    more general purpose.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.plaf.ComboBoxUI;
    import javax.swing.plaf.basic.ComboPopup;
    import javax.swing.plaf.basic.BasicComboPopup;
    import javax.swing.plaf.metal.MetalComboBoxUI;
    import com.sun.java.swing.plaf.motif.MotifComboBoxUI;
    import com.sun.java.swing.plaf.windows.WindowsComboBoxUI;
    public class CheckBoxCombo extends JComboBox {
        public CheckBoxCombo() {
            super();
        public void updateUI() {
            ComboBoxUI cui = (ComboBoxUI) UIManager.getUI(this);
            if (cui instanceof MetalComboBoxUI) {
                cui = new MyMetalComboBoxUI();
            } else if (cui instanceof MotifComboBoxUI) {
                cui = new MyMotifComboBoxUI();
            } else if (cui instanceof WindowsComboBoxUI) {
                cui = new MyWindowsComboBoxUI();
            setUI(cui);
         * You probably don't want to populate the popup here...
        protected void setupPopup(BasicComboPopup popup) {
            popup.removeAll();
            popup.add(new JCheckBoxMenuItem("One", false));
            popup.add(new JCheckBoxMenuItem("Two", true));
            popup.add(new JCheckBoxMenuItem("Three", false));
        class MyMetalComboBoxUI extends MetalComboBoxUI {
            protected ComboPopup createPopup() {
                BasicComboPopup popup = new BasicComboPopup(this.comboBox);
                setupPopup(popup);
                return popup;
        class MyWindowsComboBoxUI extends WindowsComboBoxUI {
            protected ComboPopup createPopup() {
                BasicComboPopup popup = new BasicComboPopup(this.comboBox);
                setupPopup(popup);
                return popup;
        class MyMotifComboBoxUI extends MotifComboBoxUI {
            class MotifCalendarPopup extends MotifComboBoxUI.MotifComboPopup {
                public MotifCalendarPopup(JComboBox box) {
                    super(box);
            protected ComboPopup createPopup() {
                MotifCalendarPopup popup =
                        new MotifCalendarPopup(this.comboBox);
                setupPopup(popup);
                return popup;
        public static void main(String[] args) {
            //        String defaultLAF = UIManager.getSystemLookAndFeelClassName();
            //        try {
            //            UIManager.setLookAndFeel(defaultLAF);
            //        } catch (Exception e) {
            //            e.printStackTrace();
            JFrame f = new JFrame();
            final CheckBoxCombo cc = new CheckBoxCombo();
            cc.setEditable(false);
            JPanel enablePanel = new JPanel();
            ButtonGroup buttonGroup = new ButtonGroup();
            JRadioButton b = new JRadioButton(new AbstractAction("Enabled") {
                                                  public void actionPerformed(
                                                          ActionEvent e) {
                                                      cc.setEnabled(true);
            buttonGroup.add(b);
            enablePanel.add(b);
            b.setSelected(true);
            b = new JRadioButton(new AbstractAction("Disabled") {
                                     public void actionPerformed(
                                             ActionEvent e) {
                                         cc.setEnabled(false);
            buttonGroup.add(b);
            enablePanel.add(b);
            f.getContentPane().add(enablePanel, BorderLayout.NORTH);
            f.getContentPane().add(cc);
            f.pack();
            f.show();

  • Custom JComboBox Renderer

    Hi!
    I want to use a JMenu as a renderer for a JComboBox. When the combo is pressed, the popup that is open should contain 3 JMenu. Then if the mouse id moved over any of the 3 JMenu, 2 check menu items should be opened in an additional popup, near the popup that contains the 3 JMenu.
    A picture that illustrate the behaviour could be found here: [http://www.trilulilu.ro/mogadiscio/ee847e6a14b2d5]
    I'm able to obtain the 3 JMenus in the combo's popup but the 3 JMenus does not repond to mouse events so the additional submenu is not open.
    Any suggestions are welcome.
    Orly

    package supercombo;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.util.ArrayList;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JMenu;
    import javax.swing.JToolBar;
    import javax.swing.SwingConstants;
    public class SuperCombo6 extends JComboBox {
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(500, 300);
            frame.setTitle("Super Combo 6");
            JToolBar tb = new JToolBar();
            tb.setLayout(new FlowLayout(FlowLayout.LEFT));
            tb.add(new SuperCombo6(new String[][] {
                    {"M1", "M1.1", "M1.2"},
                    {"M2", "M2.1", "M2.2"},
                    {"M3", "M3.1", "M3.2"}
            frame.getContentPane().setLayout(new BorderLayout());
            frame.getContentPane().add(tb, BorderLayout.NORTH);
            frame.setVisible(true);
        public SuperCombo6(String[][] items) {
            super(new SuperComboModel6(items.length));
            setPreferredSize(new Dimension(120, 20));
            setRenderer(new SuperComboRenderer6(items, this));
    class SuperComboModel6 extends DefaultComboBoxModel {
        private int _size;
        public SuperComboModel6(int size) {
            this._size = size;
        public int getSize() {
            return _size;
    class SuperComboRenderer6 extends DefaultListCellRenderer {
        private JLabel title;
        private ArrayList menus;
        public SuperComboRenderer6(String[][] items, final JComboBox combo) {
            title = new JLabel("SuperCombo6");
            title.setHorizontalAlignment(SwingConstants.LEFT);
            menus = new ArrayList();
            for (int i = 0; i < items.length; i++) {
                final JMenu menu = new JMenu(items[0]);
    for (int j = 1; j < items[i].length; j++) {
    JCheckBoxMenuItem item = new JCheckBoxMenuItem(items[i][j]);
    menu.add(item);
    menus.add(menu);
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    if (index == -1) {
    return title;
    JMenu menu = (JMenu) menus.get(index);
    if (isSelected) {
    menu.setSelected(true);
    } else {
    menu.setSelected(false);
    return menu;

  • JComboBox Lost Listener on Look and Feel change

    When the user change the Look And Feel on the Fly , any Listener that is done using
    myComboBox.getEditor().getEditorComponent().addXXXListener
    is lost
    I'm using Windows XP Service Pack 2, java 6 build 105
    Does someone have any inputs why this happen or how this can be "fixed" or maybe prevent. Do I'm doing something wrong?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    /* ComboBoxDemo2.java requires no other files. */
    public class ComboBoxDemo2 extends JPanel
                               implements ActionListener {
        static JFrame frame;
        JLabel result;
        String currentPattern;
        public ComboBoxDemo2() {
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
            String[] patternExamples = {
                     "dd MMMMM yyyy",
                     "dd.MM.yy",
                     "MM/dd/yy",
                     "yyyy.MM.dd G 'at' hh:mm:ss z",
                     "EEE, MMM d, ''yy",
                     "h:mm a",
                     "H:mm:ss:SSS",
                     "K:mm a,z",
                     "yyyy.MMMMM.dd GGG hh:mm aaa"
            currentPattern = patternExamples[0];
            //Set up the UI for selecting a pattern.
            JLabel patternLabel1 = new JLabel("Enter the pattern string or");
            JLabel patternLabel2 = new JLabel("select one from the list:");
            JComboBox patternList = new JComboBox(patternExamples);
            patternList.setEditable(true);
            patternList.addActionListener(this);
    //-------------------------------- XXX------------------------------------------
    //      This KeyListener it is lost when the user change the theme on the fly       
            patternList.getEditor().getEditorComponent().addKeyListener(new KeyAdapter()
            public void keyPressed(KeyEvent e)
             System.out.println(" Key pressed is "+e.getKeyCode());     
            //Create the UI for displaying result.
            JLabel resultLabel = new JLabel("Current Date/Time",
                                            JLabel.LEADING); //== LEFT
            result = new JLabel(" ");
            result.setForeground(Color.black);
            result.setBorder(BorderFactory.createCompoundBorder(
                 BorderFactory.createLineBorder(Color.black),
                 BorderFactory.createEmptyBorder(5,5,5,5)
            //Lay out everything.
            JPanel patternPanel = new JPanel();
            patternPanel.setLayout(new BoxLayout(patternPanel,
                                   BoxLayout.PAGE_AXIS));
            patternPanel.add(patternLabel1);
            patternPanel.add(patternLabel2);
            patternList.setAlignmentX(Component.LEFT_ALIGNMENT);
            patternPanel.add(patternList);
            JPanel resultPanel = new JPanel(new GridLayout(0, 1));
            resultPanel.add(resultLabel);
            resultPanel.add(result);
            patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
            resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
            add(patternPanel);
            add(Box.createRigidArea(new Dimension(0, 10)));
            add(resultPanel);
            setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
            reformat();
        } //constructor
        public void actionPerformed(ActionEvent e) {
             System.out.println("Action Event");                
            JComboBox cb = (JComboBox)e.getSource();
            String newSelection = (String)cb.getSelectedItem();
            currentPattern = newSelection;
            reformat();
        /** Formats and displays today's date. */
        public void reformat() {
             try {
            Date today = new Date();
            SimpleDateFormat formatter =
               new SimpleDateFormat(currentPattern);
                String dateString = formatter.format(today);
                result.setForeground(Color.black);
                result.setText(dateString);
            }catch (IllegalArgumentException iae) {     
            System.out.println("Ilegal argument Exception");   
            catch (Exception e) {
            System.out.println("Argument Exception");                
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            final JFrame frame = new JFrame("ComboBoxDemo2");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new ComboBoxDemo2();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setLayout(new BorderLayout());      
            //frame.setContentPane(newContentPane,BorderLayout.CENTER);
            JMenuBar menuBar = new JMenuBar();
            JMenu theme = new JMenu("Theme");
            ButtonGroup bttnGroup = new ButtonGroup();
            JCheckBoxMenuItem metal = new JCheckBoxMenuItem("Metal");
            bttnGroup.add(metal);
            metal.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
              try{
              UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
              SwingUtilities.updateComponentTreeUI(frame);
              }catch(Exception a){a.printStackTrace();}
              theme.add(metal);
            JCheckBoxMenuItem system = new JCheckBoxMenuItem("System");
            bttnGroup.add(system);
            system.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
              try{
              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              SwingUtilities.updateComponentTreeUI(frame);
              }catch(Exception a){a.printStackTrace();}
            theme.add(system);
            menuBar.add(theme);     
            frame.setJMenuBar(menuBar);
            JToolBar jtb = new JToolBar();
            jtb.add(newContentPane);
            frame.add(jtb, BorderLayout.PAGE_START);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    Thanks to both Rodney_McKay and jasper for their replys and ideas
    This code is working fine
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    /* ComboBoxDemo2.java requires no other files. */
    public class ComboBoxDemo2 extends JPanel
                               implements ActionListener {
        static JFrame frame;
        JLabel result;
        String currentPattern;
        private JComboBox patternList = new JComboBox();
        public ComboBoxDemo2() {
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
            String[] patternExamples = {
                     "dd MMMMM yyyy",
                     "dd.MM.yy",
                     "MM/dd/yy",
                     "yyyy.MM.dd G 'at' hh:mm:ss z",
                     "EEE, MMM d, ''yy",
                     "h:mm a",
                     "H:mm:ss:SSS",
                     "K:mm a,z",
                     "yyyy.MMMMM.dd GGG hh:mm aaa"
            currentPattern = patternExamples[0];
            //Set up the UI for selecting a pattern.
            JLabel patternLabel1 = new JLabel("Enter the pattern string or");
            JLabel patternLabel2 = new JLabel("select one from the list:");
            patternList = new JComboBox(patternExamples){
            public void updateUI(){
            System.out.println("UPDATE UI");
            super.updateUI();     
            changeUIAddEditorListener();
            changeUIAddEditorListener();
            patternList.setEditable(true);
            patternList.addActionListener(this);
            //Create the UI for displaying result.
            JLabel resultLabel = new JLabel("Current Date/Time",
                                            JLabel.LEADING); //== LEFT
            result = new JLabel(" ");
            result.setForeground(Color.black);
            result.setBorder(BorderFactory.createCompoundBorder(
                 BorderFactory.createLineBorder(Color.black),
                 BorderFactory.createEmptyBorder(5,5,5,5)
            //Lay out everything.
            JPanel patternPanel = new JPanel();
            patternPanel.setLayout(new BoxLayout(patternPanel,
                                   BoxLayout.PAGE_AXIS));
            patternPanel.add(patternLabel1);
            patternPanel.add(patternLabel2);
            patternList.setAlignmentX(Component.LEFT_ALIGNMENT);
            patternPanel.add(patternList);
            JPanel resultPanel = new JPanel(new GridLayout(0, 1));
            resultPanel.add(resultLabel);
            resultPanel.add(result);
            patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
            resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
            add(patternPanel);
            add(Box.createRigidArea(new Dimension(0, 10)));
            add(resultPanel);
            setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
            reformat();
        } //constructor
        public void actionPerformed(ActionEvent e) {
             System.out.println("Action Event");                
            JComboBox cb = (JComboBox)e.getSource();
            String newSelection = (String)cb.getSelectedItem();
            currentPattern = newSelection;
            reformat();
        /** Formats and displays today's date. */
        public void reformat() {
             try {
            Date today = new Date();
            SimpleDateFormat formatter =
               new SimpleDateFormat(currentPattern);
                String dateString = formatter.format(today);
                result.setForeground(Color.black);
                result.setText(dateString);
            }catch (IllegalArgumentException iae) {     
            System.out.println("Ilegal argument Exception");   
            catch (Exception e) {
            System.out.println("Argument Exception");                
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            final JFrame frame = new JFrame("ComboBoxDemo2");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new ComboBoxDemo2();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setLayout(new BorderLayout());      
            //frame.setContentPane(newContentPane,BorderLayout.CENTER);
            JMenuBar menuBar = new JMenuBar();
            JMenu theme = new JMenu("Theme");
            ButtonGroup bttnGroup = new ButtonGroup();
            JCheckBoxMenuItem metal = new JCheckBoxMenuItem("Metal");
            bttnGroup.add(metal);
            metal.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
              try{
              UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
              SwingUtilities.updateComponentTreeUI(frame);
              }catch(Exception a){a.printStackTrace();}
              theme.add(metal);
            JCheckBoxMenuItem system = new JCheckBoxMenuItem("System");
            bttnGroup.add(system);
            system.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
              try{
              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              SwingUtilities.updateComponentTreeUI(frame);
              }catch(Exception a){a.printStackTrace();}
            theme.add(system);
            menuBar.add(theme);     
            frame.setJMenuBar(menuBar);
            JToolBar jtb = new JToolBar();
            jtb.add(newContentPane);
            frame.add(jtb, BorderLayout.PAGE_START);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
       public void changeUIAddEditorListener() {
       patternList.getEditor().getEditorComponent().addKeyListener(new KeyAdapter()
       public void keyPressed(KeyEvent e)
       System.out.println(" Key pressed is "+e.getKeyCode());     
    }

  • Actionlistener for JCombobox with JCheckbox

    Hi!
    I have written a JComboBox item which holds a checkbox :
    public class CheckComboItem extends JCheckBox{
        private static final long serialVersionUID = 1677961185556377734L;
        public Integer id = 0;
        public CheckComboItem(Integer id, String text, Boolean state) {
            super(text, state);
            this.id = id;
    }This works fine; However i have problems with my action listener, which should change the checkbox' selection state.
    Unfortunately this only works sometimes (randomly) :-(
    public class CheckComboListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JComboBox cb = (JComboBox) e.getSource();
            CheckComboItem store = (CheckComboItem) cb.getSelectedItem();
            store.setSelected((!store.isSelected()));
    }Can you please tell me what i am doing wrong/ how this needs to be improved ?
    Thank you very much!

    You managed to find the Swing forum the last time you posted a Swing question.
    Why didn't you search the Swing forum this time before you posted a question?
    Maybe a JCheckBoxMenuItem will work better.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • Not Updating the Values in the JComboBox and JTable

    Hi Friends
    In my program i hava Two JComboBox and One JTable. I Update the ComboBox with different field on A Table. and then Display a list of record in the JTable.
    It is Displaying the Values in the Begining But when i try to Select the Next Item in the ComboBox it is not Updating the Records Eeither to JComboBox or JTable.
    MY CODE is this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.DefaultComboBoxModel.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    public class SearchBook extends JDialog implements ActionListener
         private JComboBox comboCategory,comboAuthor;
         private JSplitPane splitpane;
         private JTable table;
         private JToolBar toolBar;
         private JButton btnclose, btncancel;
         private JPanel panel1,panel2,panel3,panel4;
         private JLabel lblCategory,lblAuthor;
         private Container c;
         //DefaultTableModel model;
         Statement st;
         ResultSet rs;
         Vector v = new Vector();
         public SearchBook (Connection con)
              // Property for JDialog
              setTitle("Search Books");
              setLocation(40,110);
              setModal(true);
              setSize(750,450);
              // Creating ToolBar Button
              btnclose = new JButton(new ImageIcon("Images/export.gif"));
              btnclose.addActionListener(this);
              // Creating Tool Bar
              toolBar = new JToolBar();
              toolBar.add(btnclose);
              try
                   st=con.createStatement();
                   rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
                   while(rs.next())
                        v.add(rs.getString(1));
              catch(SQLException ex)
                   System.out.println("Error");
              panel1= new JPanel();
              panel1.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              lblCategory = new JLabel("Category:");
              lblCategory.setHorizontalAlignment (JTextField.CENTER);
              c.gridx=2;
              c.gridy=2;
              panel1.add(lblCategory,c);
              comboCategory = new JComboBox(v);
              comboCategory.addActionListener(this);
              c.ipadx=20;
              c.gridx=3;
              c.gridwidth=1;
              c.gridy=2;
              panel1.add(comboCategory,c);
              lblAuthor = new JLabel("Author/Publisher:");
              c.gridwidth=2;
              c.gridx=1;
              c.gridy=4;
              panel1.add(lblAuthor,c);
              lblAuthor.setHorizontalAlignment (JTextField.LEFT);
              comboAuthor = new JComboBox();
              comboAuthor.addActionListener(this);
              c.insets= new Insets(20,0,0,0);
              c.ipadx=20;
              c.gridx=3;
              c.gridy=4;
              panel1.add(comboAuthor,c);
              comboAuthor.setBounds (125, 165, 175, 25);
              table = new JTable();
              JScrollPane scrollpane = new JScrollPane(table);
              //panel2 = new JPanel();
              //panel2.add(scrollpane);
              splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
              splitpane.setDividerSize(15);
              splitpane.setDividerLocation(190);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              getContentPane().add(splitpane);
         public void actionPerformed(ActionEvent ae)
              Object obj= ae.getSource();
              if(obj==comboCategory)
                   String selecteditem = (String)comboCategory.getSelectedItem();
                   displayAuthor(selecteditem);
                   System.out.println("Selected Item"+selecteditem);
              else if(obj==btnclose)
                   setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
              else if(obj==comboAuthor)
                   String selecteditem1 = (String)comboAuthor.getSelectedItem();
                   displayavailablity(selecteditem1);
                   //System.out.println("Selected Item"+selecteditem1);
                   System.out.println("Selected Author"+selecteditem1);
         private void displayAuthor(String selecteditem)
              try
              {     Vector data = new Vector();
                   rs= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
                   System.out.println("Executing");
                   while(rs.next())
                        data.add(rs.getString(1));
                   //((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
                   comboAuthor.setModel(new DefaultComboBoxModel(data));
              catch(SQLException ex)
                   System.out.println("ERROR");
         private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        rs= st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        //DefaultTableModel model = new DefaultTableModel(data1,columnNames);
                        //table.setModel(model);
                        rs.close();
                        st.close();
                   catch(SQLException ex)
    }Please check my code and give me some Better Solution
    Thank you

    You already have a posting on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=5143235

  • JComboBox causing GTK-WARNING and GTK-CRITICAL on Ubuntu 8.04

    I was wondering why whenever I use the GTK Look and Feel, my JComboBox's cause GTK issues. They also don't display right...
    Here is the code I am using....
    import javax.swing.*;
    public class ComboBoxDisplayTest extends JFrame
      public ComboBoxDisplayTest()
        try
          UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
          SwingUtilities.updateComponentTreeUI(this);
        catch(Exception ex)
          ex.printStackTrace();
        JComboBox cb = new JComboBox();
        this.add(cb);
        cb.addItem("Item 1");
        cb.addItem("Item 2");
      public static void main(String[] args)
        ComboBoxDisplayTest c = new ComboBoxDisplayTest();
        c.pack();
        c.setVisible(true);
    }This is what get's printed onto the terminal when I run the program:
    java ComboBoxDisplayTest
    (<unknown>:7078): Gtk-WARNING **: Attempting to add a widget with type GtkButton to a GtkComboBoxEntry (need an instance of GtkEntry or of a subclass)
    (<unknown>:7078): Gtk-CRITICAL **: gtk_widget_realize: assertion `GTK_WIDGET_ANCHORED (widget) || GTK_IS_INVISIBLE (widget)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failedWhat exactly is going on?
    Is there something wrong with my code?
    Is there any way to fix this?
    Any answers are much appreciated...
    Thanks

    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6624717
    as far as i know (i am using Ubuntu 7.10 & OpenJDK 1.6.0_0-b11 & Sun JDK) not fixed yet ....
    Ronald

  • Associate Action with jcombobox item

    Is it possible to associate a particular Action with a jcombobox item (for example using setAction()). When the user selects a particular item of jcombobox, the Action must be triggered.
    regards,
    Nirvan.

    Hi,
    You can associate a particular action with a JComboBox. As per my understanding u can add one action perfrom action to combobox or itemStateChanged action
    if u add action perform action, u need to add the following method to ur logic.
    JComboBox combobox=new JComboBox();
        combobox.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
             JComboBox combo = (JComboBox)evt.getSource();
                if(combo.getSelectedItem().equals("LOCATION")) {
                A a = new A();
                a.show();
            } else if(combo.getSelectedItem().equals("HOUSE")) {
                B b= new B();
                b.show();
            });if action is ItemStateChanged then add the following method.
    combobox.addItemListener(new java.awt.event.ItemListener() {
                public void itemStateChanged(java.awt.event.ItemEvent evt) {
                    and write your logic here which one needs to be triggered when this action performed.
            });Hope this will help to you....
    Thanks & Regards,
    Maadhav..

  • Retrieving values from a JComboBox - Design question.

    I would like some design guidance on a problem that I am hoping has been solved before. Here is my situation:
    I have a JComboBox that I populate with String values from a database table. The exact set of values to be loaded into the JComboBox varies according values specified elsewhere on the GUI.
    When I select an item from the JComboBox, I need to read the database to retrieve more information. The text is not sufficient for me to identify the data I need, so I need to get the table key from somewhere.
    Is there anyway I can associate my table key with the text value inside the JComboBox and retrieve it when the user selects a drop down value from the JComboBox?
    Many thanks in advance.

    when you load the data from the db, try to get ALL the information needed: item label+item value+description. put this data into a map (a hashmap) for example using a unique identifier. For example, use a numeric index. In this case, the item value should be the index that uniquely identifies your items.
    create a simple bean that encapsulates the item contents: index+value+label, description.
    Doing this will avoid the huge db access occurences.
    hth

  • How to change font/ font color etc in a graphic object using JCombobox?

    Hello
    My program im writing recently is a small tiny application which can change fonts, font sizes, font colors and background color of the graphics object containing some strings. Im planning to use Jcomboboxes for all those 4 ideas in implementing those functions. Somehow it doesnt work! Any help would be grateful.
    So currently what ive done so far is that: Im using two classes to implement the whole program. One class is the main class which contains the GUI with its components (Jcomboboxes etc..) and the other class is a class extending JPanel which does all the drawing. Therefore it contains a graphics object in that class which draws the string. However what i want it to do is using jcombobox which should contain alit of all fonts available/ font sizes/ colors etc. When i scroll through the lists and click the one item i want - the graphics object properties (font sizes/ color etc) should change as a result.
    What ive gt so far is implemented the jcomboboxes in place. Problem is i cant get the font to change once selecting an item form it.
    Another problem is that to set the color of font - i need to use it with a graphics object in the paintcomponent method. In this case i dnt want to create several diff paint.. method with different property settings (font/ size/ color)
    Below is my code; perhaps you'll understand more looking at code.
    public class main...
    Color[] Colors = {Color.BLUE, Color.RED, Color.GREEN};
            ColorList = new JComboBox(Colors);
    ColorList.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                     JComboBox cb = (JComboBox)ev.getSource();
                    Color colorType = (Color)cb.getSelectedItem();
                    drawingBoard.setBackground(colorType);
              });;1) providing the GUI is correctly implemented with components
    2) Combobox stores the colors in an array
    3) ActionListener should do following job: (but cant get it right - that is where my problem is)
    - once selected the item (color/ font size etc... as i would have similar methods for each) i want, it should pass the item into the drawingboard class (JPanel) and then this class should do the job.
    public class DrawingBoard extends JPanel {
           private String message;
           public DrawingBoard() {
                  setBackground(Color.white);
                  Font font = new Font("Serif", Font.PLAIN, fontSize);
                  setFont(font);
                  message = "";
           public void setMessage(String m) {
                message = m;
                repaint();
           public void paintComponent(Graphics g) {
                  super.paintComponent(g);
                  //setBackground(Color.RED);
                  Graphics2D g2 = (Graphics2D) g;
                  g2.setRenderingHint             
                  g2.drawString(message, 50, 50);
           public void settingFont(String font) {
                //not sure how to implement this?                          //Jcombobox should pass an item to this
                                   //it should match against all known fonts in system then set that font to the graphics
          private void settingFontSize(Graphics g, int f) {
                         //same probelm with above..              
          public void setBackgroundColor(Color c) {
               setBackground(c);
               repaint(); // still not sure if this done corretly.
          public void setFontColor(Color c) {
                    //not sure how to do this part aswell.
                   //i know a method " g.setColor(c)" exist but i need to use a graphics object - and to do that i need to pass it in (then it will cause some confusion in the main class (previous code)
           My problems have been highlighted in the comments of code above.
    Any help will be much appreciated thanks!!!

    It is the completely correct code
    I hope that's what you need
    Just put DrawingBoard into JFrame and run
    Good luck!
    public class DrawingBoard extends JPanel implements ActionListener{
         private String message = "message";
         private Font font = new Font("Serif", Font.PLAIN, 10);
         private Color color = Color.RED;
         private Color bg = Color.WHITE;
         private int size = 10;
         public DrawingBoard(){
              JComboBox cbFont = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
              cbFont.setActionCommand("font");
              JComboBox cbSize = new JComboBox(new Integer[]{new Integer(14), new Integer(13)});
              cbSize.setActionCommand("size");
              JComboBox cbColor = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbColor.setActionCommand("color");
              JComboBox cbBG = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbBG.setActionCommand("bg");
              add(cbFont);
              cbFont.addActionListener(this);
              add(cbSize);
              cbSize.addActionListener(this);
              add(cbColor);
              cbColor.addActionListener(this);
              add(cbBG);
              cbBG.addActionListener(this);
         public void setMessage(String m){
              message = m;
              repaint();
         protected void paintComponent(Graphics g){
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.setColor(bg);//set background color
              g2.fillRect(0,0, getWidth(), getHeight());          
              g2.setColor(color);//set text color
              FontRenderContext frc = g2.getFontRenderContext();
              TextLayout tl = new TextLayout(message,font,frc);//set font and message
              AffineTransform at = new AffineTransform();
              at.setToTranslation(getWidth()/2-tl.getBounds().getWidth()/2,
                        getWidth()/2 + tl.getBounds().getHeight()/2);//set text at center of panel
              g2.fill(tl.getOutline(at));
         public void actionPerformed(ActionEvent e){
              JComboBox cb = (JComboBox)e.getSource();
              if (e.getActionCommand().equals("font")){
                   font = new Font(cb.getSelectedItem().toString(), Font.PLAIN, size);
              }else if (e.getActionCommand().equals("size")){
                   size = ((Integer)cb.getSelectedItem()).intValue();
              }else if (e.getActionCommand().equals("color")){
                   color = (Color)cb.getSelectedItem();
              }else if (e.getActionCommand().equals("bg")){
                   bg = (Color)cb.getSelectedItem();
              repaint();
    }

  • Problem with JComboBox in a JPanel

    I have a JComboBox in a JPanel (with a gridbaglayout), and I add items to the combobox:
    String[] stateList={"AL",.....};
    JCombobox stateCB=new JComboBox(stateList);
    and when I run the application, the states appear in the box, but when I click on the box, there is no drop-down list!
    any ideas?

    Is the combobox Enabled if it is then after adding it to anything set it to true cause i poersonally tried out as u have given it it works and else if it does not show a list then use the setmodel function and set the model to DefaultComboBoxModel and then add the items using a for loop

  • Problem with JComboBox in a fixed JToolBar

    Hi,
    I've created a JComboBox in a JToolBar that contains all available fonts. When I click on the drop down arrow I only see the first font and a small part of the second. The JComboBox is dropped down in fact just as far as the border of the JToolbar. All the rest isn't visible to me; it seems that they are behind the other components of my JApplet. However, if I move the JToolBar from it's position (as it's a floatable component), there's no problem at all. So I'm wondering why I can't see everything when the JToolBar is docked.... Can anyone help me?
    Thanks in advance!!
    E_J

    it seems that they are behind the other components of my JApplet.Sounds like you are mixing AWT components with your Swing application. Make sure you are using JPanel, JButton ... and not Panel, Button....

  • Problem with JComboBox in aTable Cell

    I try to put JComboBox in JTableCell,
    what i want to do is something like this...
    Question | Answer |
    1. what is your favourite | a. Pizza |
    food? | b. Hot Dog |
    2. what is your favourite | a. red |
    color? | b. blue |
    Object[][] data = {
    {"1.What is your favourite food?", new AnswerChoices(new String[]{"a.Pizza","b.Hot Dog"})},
    {"2.What is your favourite color?", new AnswerChoices(new String[]{"a.red","b.blue"})}
    here my code;
    //class AnswerChoicesCellEditor
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.Component;
    import java.awt.event.MouseEvent;
    import java.util.EventObject;
    import de.falcom.table.*;
    public class AnswerChoicesCellEditor extends AbstractCellEditor implements TableCellEditor{
         protected JComboBox mComboBox;
    public AnswerChoicesCellEditor(){
         mComboBox = new JComboBox();
         mComboBox.addActionListener(this);
         mComboBox.setEditable(false);
    public Component getTableCellEditorComponent(JTable table,Object value,boolean isSelected,int row,int column){
         if(value instanceof AnswerChoices){
              AnswerChoices a = (AnswerChoices)value;
              String[] c = a.getChoices();
              mComboBox.removeAllItems();
              for(int i=0; i < c.length; i++)
                   mComboBox.addItem(c);
                   mComboBox.setSelectedIndex(a.getAnswer());
         return mComboBox;
    public Object getCellEditorValue(){
         int nchoices = mComboBox.getItemCount();
         String[] c = new String[nchoices];
         for(int i = 0; i<nchoices; i++){
              c[i] = mComboBox.getItemAt(i).toString();
         return new AnswerChoices(c,mComboBox.getSelectedIndex());
         //return mComboBox.getSelectedItem(); //here i get but after selection there is no comboBox in tableCell
    //the Renderer class
    import javax.swing.table.TableCellRenderer;
    import javax.swing.*;
    import java.awt.Component;
    public class AnswerChoicesCellRenderer extends JComboBox implements TableCellRenderer {
         private Object curValue;
    /** Creates new AnswerChoiceCellRenderer */
    public AnswerChoicesCellRenderer() {
    setEditable(false);
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
    if (value instanceof AnswerChoices) {
    AnswerChoices nl = (AnswerChoices)value;
    String[] tList = nl.getChoices();
    if (tList != null) {
    removeAllItems();
    for (int i=0; i<tList.length; i++)
    addItem(tList[i]);
         setSelectedIndex(AnswerChoices.getAnswer());
         //this.setSelectedItem();
    //return this;
    //this.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (table != null)
    if (table.isCellEditable(row, column))
    setForeground(CellRendererConstants.EDITABLE_COLOR);
    else
    setForeground(CellRendererConstants.UNEDITABLE_COLOR);
              setBackground(table.getBackground());
    return this;
    public class AnswerChoices {
         static int ans = 0;
         String[] choices ;
    public AnswerChoices(String[]c,int a){
              choices = c;
              ans          = a;
    public AnswerChoices(String[] c){
              this(c,0);
    public String[] getChoices(){
         return choices;
    public void setAnswer(int a){
         ans = a;
    public static int getAnswer(){
         return ans;
    //the TableModel i used in my app
    import java.awt.Color;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    import javax.swing.*;
    public class FAL_Table extends JTable {
    /** Creates new FAL_Table */
    public FAL_Table(DefaultTableModel dtm) {
    super(dtm);
    setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    setRowSelectionAllowed(false);
    setColumnSelectionAllowed(false);
    setBackground(java.awt.Color.white);
    setDefaultCellEditorRenderer();
    private void setDefaultCellEditorRenderer(Class forClass, TableCellEditor editor, TableCellRenderer renderer) {
         setDefaultEditor(forClass, editor);
         setDefaultRenderer(forClass, renderer);
         private void setDefaultCellEditorRenderer() {
              // Setting default editor&renderer of Boolean
              setDefaultCellEditorRenderer(Boolean.class, new BooleanCellEditor(), new BooleanCellRenderer());
              //Setting default editor&renderer of ComboBox
              setDefaultCellEditorRenderer(JComboBox.class, new ComboBoxCellEditor( ),new ComboBoxRenderer());
              // Number class
              // Setting default editor&renderer of java.math.BigDecimal
              setDefaultCellEditorRenderer(java.math.BigDecimal.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of java.math.BigInteger
              setDefaultCellEditorRenderer(java.math.BigInteger.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of java.lang.Byte
              setDefaultCellEditorRenderer(Byte.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Double
              setDefaultCellEditorRenderer(Double.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Float
              setDefaultCellEditorRenderer(Float.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Integer
              setDefaultCellEditorRenderer(Integer.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Long
              setDefaultCellEditorRenderer(Long.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of Short
              setDefaultCellEditorRenderer(Short.class,new NumberCellEditor(), new NumberCellRenderer());
              // Setting default editor&renderer of String
              setDefaultCellEditorRenderer(String.class,new StringCellEditor(), new StringCellRenderer());
              // Setting default editor&renderer of FileName
              setDefaultCellEditorRenderer(FileName.class,new FileNameCellEditor(), new FileNameCellRenderer());
              // Setting default editor&renderer of Color
              setDefaultCellEditorRenderer(Color.class,new ColorCellEditor(), new ColorCellRenderer());
              setDefaultCellEditorRenderer(AnswerChoices.class, new AnswerChoicesCellEditor(), new AnswerChoicesCellRenderer());
              setDefaultCellEditorRenderer(JSpinner.class, new SpinnerCellEditor(), new SpinnerRenderer());
    public Class getCellClass(int row,int col) {
    TableModel model = getModel();
    if (model instanceof FAL_TableModel) {
    FAL_TableModel ptm = (FAL_TableModel)model;
    return ptm.getCellClass(row,convertColumnIndexToModel(col));
    return model.getColumnClass(convertColumnIndexToModel(col));
    public TableCellRenderer getCellRenderer(int row, int column) {
    TableColumn tableColumn = getColumnModel().getColumn(column);
    TableCellRenderer renderer = tableColumn.getCellRenderer();
    if (renderer == null) {
    renderer = getDefaultRenderer(getCellClass(row,column));
    return renderer;
    public TableCellEditor getCellEditor(int row, int column) {
    TableColumn tableColumn = getColumnModel().getColumn(column);
    TableCellEditor editor = tableColumn.getCellEditor();
    if (editor == null) {
    editor = getDefaultEditor(getCellClass(row,column));
    return editor;
    import javax.swing.table.*;
    import java.util.Vector;
    import java.awt.event.MouseEvent;
    import java.util.EventObject;
    public class FAL_TableModel extends DefaultTableModel implements TableModel {
    public FAL_TableModel() {
    this((Vector)null, 0);
    public FAL_TableModel(int numRows, int numColumns) {
    super(numRows,numColumns);
    public FAL_TableModel(Vector columnNames, int numRows) {
    super(columnNames,numRows);
    public FAL_TableModel(Object[] columnNames, int numRows) {
    super(convertToVector(columnNames), numRows);
    public FAL_TableModel(Vector data, Vector columnNames) {
    setDataVector(data, columnNames);
    public FAL_TableModel(Object[][] data, Object[] columnNames) {
    setDataVector(data, columnNames);
         public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    Object obj = getValueAt(row,col);
    if (col != 1){
    return false;
         }else{
              return true;
    public Class getCellClass(int row,int col) {
    Object obj = getValueAt(row,col);
    if (obj != null)
         return obj.getClass();
         else
         return Object.class;
    public Object getCellValue(int row,int col) {
    Object obj = getValueAt(row,col);
              return obj;      
    my problem is, when i select an item from one of the comboBox in the table the value of the other cells changes too and i have the same problem with JSpinner.
    please help i am stuck
    Gebi

    and when i try to get the current value oa a cell it returns the Component class like this
    AnswerChoices@bf1f20 ...

  • JComboBox.setPopupVisible() and focus

    Hello,
    the following code demonstrates that always when the combobox is editable and the standard focus sequence is modified, a setPopupVisible(true) indeed opens the popup, but it is immediately closed again. Is anything wrong with the code?
    Although there are quite a number of JComboBox bugs in the database, I did not find this one. If it is a bug, of course I would be interested in a workaround.
    Regards
    J�rg
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Y extends JFrame
      private JComboBox cmb;
      public Y()
      { setSize(300,300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container cp= getContentPane();
        cp.setLayout(null);
        final JCheckBox cb= new JCheckBox("Combo editable");
        cb.setBounds(80,30,130,20);
        cb.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
         cmb.setEditable(cb.isSelected());
        final JTextField tf1= new JTextField();
        tf1.setBounds(50,60,60,20);
        tf1.addFocusListener(new FocusAdapter() {
          public void focusLost(FocusEvent evt) {
         if (!tf1.getText().equals("ee")) {
           cmb.requestFocusInWindow(); // Prevents popup to stay open.
           cmb.setPopupVisible(true);
           System.out.println(cmb.isVisible());
        JTextField tf2= new JTextField();
        tf2.setBounds(150,60,60,20);
        tf2.addFocusListener(new FocusAdapter() {
          public void focusLost(FocusEvent evt) {
         cmb.setPopupVisible(true);
        cmb = new JComboBox(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"});
        cmb.setBounds(100,90,50,20);
        cmb.setSelectedIndex(-1);
        System.out.println("LightWeight: "+cmb.isLightWeightPopupEnabled());
        cp.add(cb);
        cp.add(tf1);
        cp.add(tf2);
        cp.add(cmb);
        setVisible(true);
        tf1.requestFocusInWindow();
      public static void main(String args[])
      { java.awt.EventQueue.invokeLater(new Runnable()
        { public void run()
          { new Y();
    }

    Well, there's two things I note. The first is you're printing out the comboBox's visible status, which is always true, when you're probably trying to get the comboBox's popup's visible status.
    The second thing is the cause of your problem. You request focus on the combo box. When it is editable, however, it is the editor component that gets the focus, not the combo box. So, the popup is made visible and then the editor component loses focus because the combo box gets focus, and so the popup is hidden.
    This change does what you want, I think:
        tf1.addFocusListener(new FocusAdapter() {
          public void focusLost(FocusEvent evt) {
        if (!tf1.getText().equals("ee")) {
            if ( cmb.isEditable() )
                cmb.getEditor().getEditorComponent().requestFocusInWindow();
            else
                cmb.requestFocusInWindow(); // Prevents popup to stay open.
          cmb.setPopupVisible(true);
          System.out.println(cmb.isVisible());
        });

  • JComboBox popup list remains open after losing keyboard focus

    Hi,
    I have noticed a strange JComboBox behavior. When you click on the drop down arrow to show the popup list, and then press the Tab key, the keyboard focus moves to the next focusable component, but the popup list remains visible.
    I have included a program that demonstrates the behavior. Run the program, click the drop down arrow, then press the Tab key. The cursor will move into the JTextField but the combo box's popup list is still visible.
    Does anyone know how I can change this???
    Thanks for any help or ideas.
    --Yeath
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class Test extends JFrame
       public Test()
          super( "Test Application" );
          this.getContentPane().setLayout( new BorderLayout() );
          Box box = Box.createHorizontalBox();
          this.getContentPane().add( box, BorderLayout.CENTER );
          Vector<String> vector = new Vector<String>();
          vector.add( "Item" );
          vector.add( "Another Item" );
          vector.add( "Yet Another Item" );
          JComboBox jcb = new JComboBox( vector );
          jcb.setEditable( true );
          JTextField jtf = new JTextField( 10 );
          box.add( jcb );
          box.add( jtf );
       public static void main( String[] args )
          Test test = new Test();
          test.pack();
          test.setVisible( true );
          test.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }

    ran your code on 1.5.0_3, observed problem as stated.
    even though the cursor is merrily blinking in the textfield, you have to click into
    the textfield to dispose the dropdown
    ran your code on 1.4.2_08, no problems at all - tabbing into textfield immediately
    disposed the dropdown
    another example of 'usual' behaviour (involving focus) breaking between 1.4 and 1.5
    the problem is that any workaround now, may itself be broken in future versions

Maybe you are looking for