ComboBox, setSelectedIndex...

Hello,
I have a problem with the JComboBox.
When I do : jcomboBox.setSelectedIndex(0), it doesn't change the combobox .
Can someone help me ??

When I do : jcomboBox.setSelectedIndex(0), it doesn't change the combobox . Are you suggesting that a basic method like setSelectedIndex(0) isn't working? Don't you think other people would have noticed this before?
So the the problem must be with you code and since you didn't post the sample program you are using to test this method, there is no way we can help you.

Similar Messages

  • Combobox dropdown functionality

    Hi,
    I have a combobox dropdown for a Column in my table. it displays "codes Description" something like this
    01 Apparel
    02 Houseware
    03 Kitchenware
    I have a query to get this data in the dropdown from a oracle table.
    Select LEVEL1_CATEGORY_CD, CATEGORY_DESC From PRODUCT_CATEGORY1
    Order By PRODUCT_CATEGORY1.CATEGORY_DESC
    I am using setboundsql() method of the Column class in Quicktable.
    http://quicktable.org/doc/quick/dbtable/Column.html
    I have also tried getting the query data in a hastable as a key/value pair and fill the combo box.
    what i need is when user selects something from the dropdown like "02 Houseware" i need only 02 to be filled into my cell. is this possible? right now its filling "02 Houseware" in the dropdown. can you explain stepwise as i am new to swing API.
    Thanks.

    I guess I am close but doing something silly. thats how I learn.
    here is my code snippet,
    final JComboBox comboBox;
             comboBox = new JComboBox( model );   // model.addElement(rs.getString(1));
             comboBox.setEditable(true);
             comboBox.setSelectedIndex(-1);
          comboBox.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
         if (comboBox.getSelectedIndex()==-1) return;
         String s= comboBox.getSelectedItem().toString().trim();
        comboBox.setSelectedItem(s.substring(0,2));
          c.setCellEditor(new DefaultCellEditor(comboBox));   //c = dBTable1.getColumn(1);My vector has elements like, "01 Apparel".
    I am able to get these in the dropdown. when i select something, its filling, 01 Apparel . after selecting if i click the cell again, then its changing to 01(as i needed). else after selecting if i lose focus and go to other cell, the value remains as 01 Apparel.
    this might be trivial for someone who knows Swing but I am gettting frustrated...have to read complete tutorial this weeknd :)
    Thanks again.

  • EditableJComboBox

    I'm using an editable combobox with about 8000 items.
    Then it's quite difficult to select the disired item in the list. I'd like the combo box to follow me while typing:
    i.e. if i type "M", I want the combobox to display the first item starting wiyh M, but if i type "MI", I want the combo box to display the first item starting with MI and so on.
    Is it possible with an editable combobox or should I change component?
    Please help me, I'm really in trouble!
    Thank you in advance.
    Emanuele

    if you add a keyListener to the ComboBox and then use that to go to the letter pressed then you can do it like this:    BuySellComboBox.addKeyListener(new java.awt.event.KeyAdapter() {
          public void keyReleased(KeyEvent e) {
            BuySellComboBox_keyPressed(e);
      void BuySellComboBox_keyPressed(KeyEvent e) {
        char typed = e.getKeyChar();
        switch (typed) {
          case ('b'):
         BuySellComboBox.setSelectedIndex(1);
         break;
          case ('s'):
         BuySellComboBox.setSelectedIndex(2);
         break;
          default:
         BuySellComboBox.setSelectedIndex(0);
      }As you can see my combo box only has buy or sell as it's options though, if you want to search on more letters then just add the char from the key pressed to a string and then write a for for loop that searches the ComboBox until it finds :those letters:
    int row=0;
    String myLetters="mi";
    for (int x=0;x<ComboBox.getMaximumRowCount();x++){
       if (ComboBox.getSelectedItem().toString().subString(0,myLetters.length()).equalsIgnoreCase(myLetters)) {
          row=x;
          break;
    ComboBox.setSelectedIndex(row);However what if the person types some letters, then changes their mind and types a different letter?
    Hope you can do something with this.
    If not you may want to use a JList.
    regards,
    Ben.

  • How is it possible to show contents of JComboBox that aren't in list

    I have an application that I have developed over time that requires that I be able to select any item in a JComboBox list and send an actionEvent. In order to do this I set the value of the JComboBox selectedIndex to -1 indicating no selection. This enables me to select the first item in the list and send an actionEvent. The only problem is that the window where the items for the box appears is initially blank. (I don't know if window is the correct term). I would like the ability to place a message in this window such as "Please Select FooBar". Anyone know how to do this?

    Maybe something like this:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.*;
    public class ComboBoxPrompt extends JFrame implements ActionListener
         JComboBox comboBox;
         public ComboBoxPrompt()
              String[] items = { "Bryan", "Nick", "Tom" };
              comboBox = new JComboBox( items );
              comboBox.setSelectedIndex(-1);
              comboBox.setRenderer( new PromptRenderer("Select Person") );
              getContentPane().add( comboBox, BorderLayout.NORTH );
              JButton button = new JButton("Clear Selection");
              getContentPane().add( button, BorderLayout.SOUTH );
              button.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              comboBox.setSelectedIndex(-1);
         public static void main(String[] args)
              JFrame frame = new ComboBoxPrompt();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
         class PromptRenderer extends BasicComboBoxRenderer
              private String prompt;
              public PromptRenderer(String prompt)
                   this.prompt = prompt;
              public Component getListCellRendererComponent(
                   JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
                   super.getListCellRendererComponent(list,
                        value, index, isSelected, cellHasFocus);
                   if (value == null)
                        setText( prompt );
                   return this;
    }

  • DefaultCellEditor in JTable can not update itself when the value changes

    Hi,
    I have a JTable which has 4 columns. The 3rd column has a comboBox. whenever I select an item from the first row, the cell at (currentrow, 4thcolumn) will be updated according to the item selected.
    Now the problem is, after selecting the item in any cell with 3rd column, the row is updated correctly, but then all comboBox in column 3 are gone! I cannot figure out what causes this. Please help! Any suggestion will be greatly appreciated!
    Jing

    Thanks! Could you give more details on how to use the second approach?
    I have a table with two columns, one called ID and the other called Value. I'm using JComboBox for the Value column. Whenever I select an item from the comboBox, I want the value in the cell under the ID column to change value to the value selected in the comboBox.
    The problem I'm having now is although I can change the value in the comboBox and which triggers the event to change the value under the ID column, when I click the comboBox of another row, the cell under ID of the previous row changed also, before the value under ID of the current selected row.
    I think the problem is there is no distinct comboBox for each row of the table. Seems like when one box change and trigger an event, that event performed in every other rows in the table.
    Following is the code:
    public class Test extends JPanel{
         DefaultTableModel tm;
         JTable table;
         JScrollPane nscrollPane;
         public int total=4;
         public Vector datavec, thvec;
         public Test(Vector datavec, Vector thvec){
              this.datavec=datavec;
              this.thvec=thvec;
         tm = new DefaultTableModel(datavec,thvec);
              table = new JTable(tm);
              table.addMouseListener(new PopupListener(table));
    // table.addMouseListener(new PopupListener(table));
    //tm.setTableHeader(table.getTableHeader()); //ADDED THIS
    int height = table.getRowHeight()*table.getRowCount();
    table.setPreferredScrollableViewportSize(new Dimension(500, height));
    //Create the scroll pane and add the table to it.
    nscrollPane = new JScrollPane(table);
    setUpNNColumn(table, table.getColumnModel().getColumn(1));
    //Add the scroll pane to this panel.
    add(nscrollPane);
    public void updateLabel(Integer size)
         int r=table.getSelectedRow();
         if(r!=-1)
         ((Vector)datavec.elementAt(r)).setElementAt(size, 0);
         repaint();
    public void setUpNNColumn(JTable table, TableColumn nnColumn) {
              //Set up the editor for the sport cells
              JComboBox comboBox = new JComboBox();
              comboBox.addActionListener(new ComboBoxListener());
              int num=total/2;
              for(int i=0; i<2; i++){
                   comboBox.addItem(new Integer(num*(i+1)));
              comboBox.setSelectedIndex(1);
              nnColumn.setCellEditor(new DefaultCellEditor(comboBox));
    private class ComboBoxListener implements ActionListener{
         public void actionPerformed(ActionEvent e)
              JComboBox cb = (JComboBox)e.getSource();
    Integer size = (Integer)cb.getSelectedItem();
         updateLabel(size);
    private static void createAndShowGUI(Vector a, Vector b) {
    \ JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("Nearest Neighbor Fact Table");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    Test newContentPane = new Test(a, b);
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
         int patidx, hitnum=2;
         Vector a=new Vector();
         Vector a1=new Vector();
         Vector a2=new Vector();
         a1.add(new Integer(1));
         a1.add(new Integer(4));
         a.add(a1);
         a2.add(new Integer(2));
         a2.add(new Integer(4));
         a.add(a2);
         Vector b=new Vector();
         b.add("ID");
         b.add("Value");
         //StatTableGUI.createAndShowGUI(gd);
         Test.createAndShowGUI(a,b);
    Any suggestions? Thanks!
    Jing

  • GridBagLayout with Panels

    In a nutshell I have five panels. The comboPanel contains a label and comboBox; objectPanel has a label and text field; filePanel and directPanel have a label, text field and button; buttonPanel has two buttons.
    When the program is first run only the comboPanel is visible. If "Display object and filePanel" is selected from the comboBox then the objectPanel and filePanel are visible, else directPanel is visible. buttonPanel is visible no matter what is selected.
    The problem is I am trying to add them to the GridBayLayout and have them display below one another which is why I am using gbc.gridwidth = GridBagConstraints.REMAINDER for each, however they are all showing up on the same line.
    Thanks in advance
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SMG3AuditInterface extends JFrame
        JComboBox comboBox;
        JLabel lblComponent, lblObjectName, lblFileName, lblDirectName;
        JTextField tfObjectName, tfFileName, tfDirectName;
        JButton btnSubmit, btnCancel, btnFileBrowse, btnDirectBrowse;
        JPanel comboPanel, objectPanel, filePanel, directPanel, buttonPanel;
        GridBagLayout gb;
        GridBagConstraints gbc;
        public SMG3AuditInterface()
        gb = new GridBagLayout();
        gbc = new GridBagConstraints();
        Container cp = getContentPane();
        cp.setLayout(gb);
        String components[] = {"Display directPanel",
            "Display object and filePanel"};
        comboBox = new JComboBox(components);
        comboBox.setSelectedIndex(-1);
        lblComponent = new JLabel("Component Type: ");
        comboPanel = new JPanel();
        comboPanel.add(lblComponent);
        comboPanel.add(comboBox);
        cp.add(comboPanel);
        lblObjectName = new JLabel("Object name: ");
        tfObjectName = new JTextField(20);
        objectPanel = new JPanel();
        objectPanel.add(lblObjectName);
        objectPanel.add(tfObjectName);
        cp.add(objectPanel);
        objectPanel.setVisible(false);
        lblFileName = new JLabel("XML Filename: ");
        tfFileName = new JTextField(20);
        btnFileBrowse = new JButton("Browse");
        filePanel = new JPanel();
        filePanel.add(lblFileName);
        filePanel.add(tfFileName);
        filePanel.add(btnFileBrowse);
        cp.add(filePanel);
        filePanel.setVisible(false);
        lblDirectName = new JLabel("XML Directory name: ");
        tfDirectName = new JTextField(20);
        btnDirectBrowse = new JButton("Browse");
        directPanel = new JPanel();
        directPanel.add(lblDirectName);
        directPanel.add(tfDirectName);
        directPanel.add(btnDirectBrowse);
        cp.add(directPanel);
        directPanel.setVisible(false);
        btnSubmit = new JButton("Submit");
        btnCancel = new JButton("Cancel");
        buttonPanel = new JPanel();
        buttonPanel.add(btnSubmit);
        buttonPanel.add(btnCancel);
        cp.add(buttonPanel);
        buttonPanel.setVisible(false);
        gbc.gridx = GridBagConstraints.RELATIVE;
        gbc.gridy = GridBagConstraints.RELATIVE;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.ipadx = 0;
        gbc.ipady = 0;
        gbc.gridwidth = 3;
        gbc.gridheight = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gb.setConstraints(comboPanel, gbc);
        add(comboPanel);
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.gridheight = 1;
        gb.setConstraints(objectPanel, gbc);
        add(objectPanel);
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.gridheight = 2;
        gb.setConstraints(filePanel, gbc);
        add(filePanel);
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.gridheight = 2;
        gb.setConstraints(directPanel, gbc);
        add(directPanel);
        gbc.gridwidth = 2;
        gbc.gridheight = 1;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gb.setConstraints(buttonPanel, gbc);
        add(buttonPanel);
        comboBox.addItemListener(new ItemListener()
           public void itemStateChanged(ItemEvent e)
              JComboBox cb = (JComboBox)e.getSource();
              String itemName = (String)cb.getSelectedItem();
              buttonPanel.setVisible(true);
              if (itemName == "Display object and filePanel")
                 objectPanel.setVisible(true);
                 filePanel.setVisible(true);
                 directPanel.setVisible(false);
              else
                 objectPanel.setVisible(false);
                 filePanel.setVisible(false);
                 directPanel.setVisible(true);
        public static void main(String[] args)
        SMG3AuditInterface ai = new SMG3AuditInterface();
        ai.setDefaultCloseOperation(ai.EXIT_ON_CLOSE);
        ai.setLocation(400, 300);
        ai.setPreferredSize(new Dimension(400,300));
        ai.pack();
        ai.show();
    }

    Here's an example:
    import java.awt.BorderLayout;
    import java.awt.CardLayout;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class SMG3Petes extends JPanel
        private static final String DIRECT_PANEL = "Display directPanel";
        private static final String OBJECT_FILE_PANEL = "Display object and filePanel";
        private static final String components[] =
            DIRECT_PANEL, OBJECT_FILE_PANEL
        private static final String SUBMIT = "Submit";
        private static final String CANCEL = "Cancel";
        private static final String EMPTY_PANEL = "Empty Panel";
        private JPanel centerPanel;
        private CardLayout cardlayout = new CardLayout();
        private JComboBox comboBox;
        private JButton submitBtn = new JButton(SUBMIT);
        private JButton cancelBtn = new JButton(CANCEL);
        private JTextField tfObjectName = new JTextField(20);
        private JTextField tfFileName = new JTextField(20);
        private JTextField tfDirectName = new JTextField(20);
        public SMG3Petes()
            int eb = 15;
            setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
            setLayout(new BorderLayout());
            add(createBigCenterPanel(), BorderLayout.CENTER);
            add(createPageEndPanel(), BorderLayout.PAGE_END);
        private JPanel createBigCenterPanel()
            JPanel p = new JPanel();
            p.setLayout(cardlayout);
            p.add(new JPanel(), EMPTY_PANEL);
            p.add(createObjectFilePanel(), OBJECT_FILE_PANEL);
            p.add(createDirectPanel(), DIRECT_PANEL);
            centerPanel = p;
            return p;
        private JPanel createObjectFilePanel()
            JPanel p = new JPanel();
            p.setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.gridheight = 1;
            gbc.gridwidth = 1;
            gbc.weightx = 1;
            gbc.weighty = 1;
            gbc.insets = new Insets(5, 5, 5, 5);
            p.add(new JLabel("Object name: "), gbc);
            gbc.gridx = 1;
            gbc.gridwidth = 2;
            gbc.weightx = 2;
            p.add(tfObjectName, gbc);
            gbc.gridx = 3;
            gbc.gridwidth = 1;
            gbc.weightx = 1;
            p.add(new JLabel("   "));
            gbc.gridx = 0;
            gbc.gridy = 1;
            gbc.gridwidth = 1;
            gbc.weightx = 1;
            p.add(new JLabel("XML Filename: "), gbc);
            gbc.gridx = 1;
            gbc.gridwidth = 2;
            gbc.weightx = 2;
            p.add(tfFileName, gbc);
            gbc.gridx = 3;
            gbc.gridwidth = 1;
            gbc.weightx = 1;
            JButton browseBtn = new JButton("Browse");
            p.add(browseBtn, gbc);
            return p;
        private JPanel createDirectPanel()
            JPanel p = new JPanel(new FlowLayout(FlowLayout.CENTER, 25, 0));
            JLabel lblDirectName = new JLabel("XML Directory name: ");
            tfDirectName = new JTextField(20);
            JButton btnDirectBrowse = new JButton("Browse");
            p.add(lblDirectName);
            p.add(tfDirectName);
            p.add(btnDirectBrowse);
            return p;
        private JPanel createPageEndPanel()
            JPanel p = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 0));
            p.add(createComboPanel());
            p.add(createButtonPanel());
            return p;
        private JPanel createComboPanel()
            comboBox = new JComboBox(components);
            comboBox.setSelectedIndex(-1);
            comboBox.addItemListener(new ComboItemListener());
            JPanel p = new JPanel();
            p.add(new JLabel("Component Type: "));
            p.add(comboBox);
            return p;
        private class ComboItemListener implements ItemListener
            public void itemStateChanged(ItemEvent ie)
                submitBtn.setEnabled(true);
                cancelBtn.setEnabled(true);
                String itemName = (String) comboBox.getSelectedItem();
                if (itemName.equals(DIRECT_PANEL))
                    cardlayout.show(centerPanel, DIRECT_PANEL);
                else if (itemName.equals(OBJECT_FILE_PANEL))
                    cardlayout.show(centerPanel, OBJECT_FILE_PANEL);
        private JPanel createButtonPanel()
            JPanel p = new JPanel(new GridLayout(1, 0, 15, 0));
            submitBtn.setEnabled(false);
            cancelBtn.setEnabled(false);
            p.add(submitBtn);
            p.add(cancelBtn);
            return p;
        private static void createAndShowGUI()
            JFrame frame = new JFrame("SMG3 Petes1234 Application");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new SMG3Petes());
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }

  • Help with JButton

    I want to link a button to a web page
    making a button and adding ActionListener to it is ok from there how do i proceed.
    Thanks.

    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class URL_Demo extends JFrame {
        public URL_Demo() {
            initComponents();
        private void initComponents() {
            setTitle("URL Connect");
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            toolbar = new JPanel();
            tabbedpane = new JTabbedPane();
            combobox = new JComboBox();
            combobox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
                "http://news.bbc.co.uk/sport1/hi/football/teams/a/arsenal/default.stm" ,
                        "http://www.amazon.com/",
                        "http://www.jackinworld.com/",
            combobox.setPreferredSize(new java.awt.Dimension(500, 22));
            combobox.setSelectedIndex(0);
            combobox.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    displayPage();
            toolbar.add(combobox);
            getContentPane().add(toolbar, BorderLayout.NORTH);
            getContentPane().add(tabbedpane);
            setExtendedState(JFrame.MAXIMIZED_BOTH);
            setVisible(true);
            displayPage();
        private void displayPage() {
            urlString = combobox.getSelectedItem().toString();
            setCursor(Cursor.WAIT_CURSOR);
            URL url = null;
            InputStream input = null;
            try{
                url = new URL( urlString );
            }catch(MalformedURLException ex){
                ex.printStackTrace();
            StringBuffer strb = null;
            try{
                try{
                    input = url.openStream();
                }catch(UnknownHostException ex){
                if( input != null ){
                    int c = input.read();
                    strb = new StringBuffer();
                    while( c != -1 ){
                        char cc = (char)c;
                        strb.append(cc);
                        c = input.read();
            }catch(IOException ex){
                ex.printStackTrace();
            scrollpane = new JScrollPane();
            tabbedpane.add(scrollpane);
            tabbedpane.setTitleAt(count++, urlString);
            editorpane = new JEditorPane();
            editorpane.setEditable(false);
            editorpane.setContentType("text/html");
            scrollpane.setViewportView(editorpane);
            if( strb != null ){
                editorpane.setText(strb.toString());
            }else{
                Toolkit.getDefaultToolkit().beep();
                String htmlText =
                        "<html>"
                        +"<body BGCOLOR=\"#ffffe0\">"
                        +"<br>Connection failed: <br> " +urlString+
                        "<br><br>Make sure you are connected to the Internet"
                        +"</body>"
                        +"</html>";
                editorpane.setText(htmlText);
            setCursor(Cursor.DEFAULT_CURSOR);
        public static void main(String args[]) {
            new URL_Demo();
        private String urlString;
        private JEditorPane editorpane;
        private JPanel toolbar;
        private JTabbedPane tabbedpane;
        private JComboBox combobox;
        private JScrollPane scrollpane;
        private int count;
    }

  • Problem with database functions after disposing frames.....

    Hello,
    I have some problems with hangups with my app after disposing some frames...
    My scenario is something like this:
    - i have a login frame which instantiates some other application module and it disposes itself with some code like:
    this.dispose();
    this.finalize();
    System.runFinalization();
    System.gc();
    - after that the new instantiated module frame can return to the login frame by disposing itself and instantiating again the login frame with the same code like above
    my problem is that after some 2-3 tryes to login to a module - retun to login - login to module - return to module my app hangs on some code like:
    combobox.setSelectedIndex(0);
    or
    queryDataSet.executeQuery();
    i have to mention that i use a DataModule.
    do u have any ideas?
    thanks in advance.
    adrian

    >
    - i have a login frame which instantiates some other
    application module and it disposes itself with some
    code like:
    this.dispose();
    this.finalize();
    System.runFinalization();
    System.gc();
    Sounds like a bad idea all around.
    Finalize is supposed to be called by the gc - not by you.
    Almost always using finalize is either pointless or will cause memory leaks.
    do u have any ideas?
    I would guess it has nothing to do with JDBC.
    Are you catching SQLException and printing them out? If not then do so.
    If you are do you see any exceptions? If not then it isn't JDBC.

  • BasicComboPopup issue

    Between J2SE 1.5 and Java SE 6 the implementation of javax.swing.plaf.basic.BasicComboPopup changed in a way which breaks our application. The specific change is in the internal InvocationMouseHandler class which causes the popup to hide/unhide. In releases prior to SE 6 it didn't matter if the user clicked on an item that was already selected or not. If the user clicked an item in the popup list, the JComboBox always recieveid a setSelectedIndex() call. This, in turn, not only hid the popup but sent an ActionPerformed event. In SE 6 the BasicComboPopup mouse handler now checks to see if the user clicked on a "different" item than was perviously selected. If it is the same item, the BasicComboPopup simply closes the popup and bypasses the setSelectedIndex() call which, in turn, bypasses the action event. Since nothing "haoppens" in a class that's easy to override in the GUI application I'm a little stuck.
    For those who will ask, this manifests itself in our application when users use the keyboard to type-and-narrow to an item or arrow down to an item and then use the mouse to click the selection after the keyboard has been used. When this happens, the combo box simply closes without actually firing the action event. (Yes, they can hit ENTER from there and it works. However, users being users, they immediately noted this change in behavior and requested a "fix". No, I'm not exactly sure why if someone uses the keyboard to navigate to an item that they would want to then use the mouse to select the item they've already navigated to with the keyboard) It is a pretty narrow problem since the issue only happens if the last "keybord selected" item in the list is the one the user clicks. Nonetheless, its a change in the UI behavior that was unexcpected to us and turns out to be hard to solve.
    So...
    It would seem that I should be able to make my own version of BasicComboPopup with mouse handler behavior that I want and plug it into the UIManager or the LookAndFeel somewhere. I looked at the available keys in the LookAndFeelDefaults and didn't see anything that would do the trick.
    Can anyone point me in the right direction if I want to plug my own BasicComboPopup in somewhere?

    After taking another look I have a third and I think more appropriate work-around for the specific problem originally posted in this thread and in the java bug mentioned in this thread. It is what I was originally looking for. I basically made the JComboBox behave as it did prior to 1.6 by creating my own custom BasicComboPopup by extending it and replacing the mouse handling. As follows...
    First, I made my own custom ComboBoxUI which extends BasicComboBoxUI. This allows me to generate my custom Popup from the combo box...
    // MyBasicComboBoxUI.java
    import javax.swing.plaf.basic.BasicComboBoxUI;
    import javax.swing.plaf.basic.ComboPopup;
    public class MyBasicComboBoxUI extends BasicComboBoxUI {
        protected ComboPopup createPopup() {
            return new MyBasicComboPopup( comboBox );
    }// MyBasicComboBoxUI.java Next, I created my own ComboPopup which extends BasicComboPopup. This allows me to roll back the mouseReleased() changes made in 1.6 that changed the behavior in ways I didn't like. All of this code is basically replicated from the BasicComboPopup since the Handler class is private in BasicComboBox and could not be extended. Additionally the getHandler() method is private so I had to reimplement the createxxxMouseListerner() methods.
    // MyBasicComboPopup.java
    import javax.swing.plaf.basic.BasicComboPopup;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.SwingUtilities;
    public class MyBasicComboPopup extends BasicComboPopup {
        private MouseHandler handler;
        public MyBasicComboPopup( JComboBox combo )      {
            super(combo);
        protected MouseListener createMouseListener() {
            return getMouseHandler();
        protected MouseListener createListMouseListener()     {
            return getMouseHandler();
        private MouseHandler getMouseHandler()     {
            if (handler == null) {
                handler = new MouseHandler();
            return handler;
        private class MouseHandler implements MouseListener {
            public void mouseEntered(MouseEvent e) {}
            public void mouseExited(MouseEvent e) {}
            public void mouseClicked(MouseEvent e) {}
            public void mousePressed(MouseEvent e) {
                if (e.getSource() == list)     {
                    return;
                if (!SwingUtilities.isLeftMouseButton(e) || !comboBox.isEnabled())
                    return;
                if ( comboBox.isEditable() ) {
                    Component comp = comboBox.getEditor().getEditorComponent();
                    if ((!(comp instanceof JComponent)) || ((JComponent)comp).isRequestFocusEnabled()) {
                        comp.requestFocus();
                } else
                if (comboBox.isRequestFocusEnabled())     {
                    comboBox.requestFocus();
                togglePopup();
            public void mouseReleased(MouseEvent e) {
                if (e.getSource() == list) {
                    if (list.getModel().getSize() > 0) {
                       comboBox.setSelectedIndex( list.getSelectedIndex() );
                    comboBox.setPopupVisible(false);
                    // workaround for cancelling an edited item (bug 4530953)
                    if (comboBox.isEditable() && comboBox.getEditor() != null) {
                        comboBox.configureEditor(comboBox.getEditor(), comboBox.getSelectedItem());
                    return;
                // JComboBox mouse listener
               Component source = (Component)e.getSource();
                Dimension size = source.getSize();
                Rectangle bounds = new Rectangle( 0, 0, size.width - 1, size.height - 1 );
                if ( !bounds.contains( e.getPoint() ) ) {
                    MouseEvent newEvent = convertMouseEvent( e );
                    Point location = newEvent.getPoint();
                    Rectangle r = new Rectangle();
                    list.computeVisibleRect( r );
         if ( r.contains( location ) ) {
                       comboBox.setSelectedIndex( list.getSelectedIndex() );
         comboBox.setPopupVisible(false);
                hasEntered = false;
                stopAutoScrolling();
    // MyBasicComboPopup.javaFinally, I set my custom UI as the JComboBox UI
    JComboBox c = new JComboBox();
    c.setUI(NewMyBasicComboBoxUI());

  • Editable combo box - changing list

    hey all,
    I have to capture a code, which may be one of many types, and have planned on using an editable combo box, which narrows down the available options as the user types into it - as many programs use.
    Problem is that I'm not sure what it is I need to do to make this work. So far I've got my own ComboBoxModel implementation, and I had tried listening to edit changes, and changing the list based on that. Problem is I cant mutate in the middle of the notification, so no luck there.
    Anyone have any ideas how to make this work?
    cheers
    dim

    ttarola:
    I'm not sure if I've misinterpreted your advice, but I couldn't get it to work... here's what I've done:
    public class TestKeyListener extends KeyAdapter
      private int lastItemIndex = -2;
      private final JComboBox comboBox;
      public TestKeyListener(JComboBox comboBox)
        this.comboBox = comboBox;
       * Invoked when a key has been released.
       * As you are typeing in this field it tries to help you to coomplete the
       * expression you are looking for.
      public void keyReleased(KeyEvent e)
        int keyCode = e.getKeyCode();
        JTextField editBox = (JTextField) comboBox.getEditor().getEditorComponent();
        String typedText = editBox.getText();
        int typedTextLength = typedText.length();
        // nothing has been written
        if (typedTextLength == 0)
          comboBox.setSelectedItem("");
          return;
        boolean isDelete = ((keyCode == e.VK_DELETE) || (keyCode == e.VK_BACK_SPACE));
        if (isDelete || (e.getKeyText(keyCode).length() == 1))
          String item;
          for (int i = 0; i < comboBox.getItemCount(); i++)
            item = comboBox.getItemAt(i).toString();
            if (item.startsWith(typedText))
              // after deleting the same item is the actual one
              if (isDelete && lastItemIndex == i)
                return;
              lastItemIndex = i;
              comboBox.setSelectedIndex(lastItemIndex);
              editBox.setText(item);
              editBox.setCaretPosition(typedTextLength);
              editBox.select(typedTextLength, item.length());
              return;
      public static void main(String[] args)
        final JFrame frame = new JFrame("test2");
        frame.addWindowListener(new WindowAdapter()
          public void windowClosing(WindowEvent ev)
            frame.dispose();
            System.exit(0);
        JComboBox comboBox = new JComboBox();
        for (int j = 0; j < 50; j++)
          if (j % 10 == 0) comboBox.addItem("A" + j / 10 + "77" + j);
          if (j % 10 == 1) comboBox.addItem("B" + j / 10 + "77" + j);
          if (j % 10 == 2) comboBox.addItem("C" + j / 10 + "77" + j);
          if (j % 10 == 3) comboBox.addItem("D" + j / 10 + "77" + j);
          if (j % 10 == 4) comboBox.addItem("E" + j / 10 + "77" + j);
        comboBox.setEditable(true);
        comboBox.addKeyListener(new TestKeyListener(comboBox));
        frame.setBounds(1, 1, 500, 300);
        frame.getContentPane().setLayout(new FlowLayout());
        frame.getContentPane().add(comboBox);
        frame.setVisible(true);
    }this doesn't really bother me, as the other poster has solved my problem (see next post)...
    cheers
    dim
    cheers
    dim

  • Combo boxes with number of jtree models

    Hi
    Does anyone off hand know of a good illustrative tutorial of how to make a JComboBox control setModel on a JTree.
    The idea is so when One is selected the first TreeModel is used, when Two is selected the second and so forth.
    If anyone could steer me in the right direction it would help me a great deal at this point. Thanks.

    Here's a rather ugly example:import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    public class Test extends JFrame {
        public Test() {
            super("Test");
            setContentPane(new TestPanel());
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            pack();
            setLocationRelativeTo(null);
            setVisible(true);
        private class TestPanel extends JPanel {
            private JComboBox comboBox;
            private JTree tree;
            public TestPanel() {
                tree = new JTree();
                Integer[] depths = new Integer[8];
                for (int i = 0; i < depths.length; i++) {
                    depths[i] = i;
                comboBox = new JComboBox(depths);
                comboBox.setSelectedIndex(3);
                comboBox.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        replaceTreeModel();
                replaceTreeModel();
                setLayout(new BorderLayout());
                add(new JScrollPane(tree));
                add(comboBox, BorderLayout.SOUTH);
            private void replaceTreeModel() {
                tree.setModel(new TestTreeModel((Integer) comboBox.getSelectedItem()));
        // my apologies for this tree model - I just wanted to hack something
        // together rather quickly [this doesn't look like production code :)]
        private class TestTreeModel implements TreeModel {
            private String name;
            private TestTreeModel[] children;
            public TestTreeModel(int depth) {
                this("root", 0, depth);
            private TestTreeModel(String name, int d, int depth) {
                this.name = name + " (" + d + ")";
                if (d == depth) {
                    children = new TestTreeModel[0];
                } else {
                    children = new TestTreeModel[5];
                    for (int i = 0; i < children.length; i++) {
                        children[i] = new TestTreeModel(Character.toString((char) ('a' + i)), d + 1, depth);
            public Object getRoot() {
                return this;
            public Object getChild(Object parent, int index) {
                return ((TestTreeModel) parent).children[index];
            public int getChildCount(Object parent) {
                return ((TestTreeModel) parent).children.length;
            public boolean isLeaf(Object node) {
                return getChildCount(node) == 0;
            public void valueForPathChanged(TreePath path, Object newValue) {
                // can't happen
            public int getIndexOfChild(Object parent, Object child) {
                for (int i = 0; i < getChildCount(parent); i++)
                    if (getChild(parent, i) == child)
                        return i;
                return -1;
            public void addTreeModelListener(TreeModelListener l) {
                // never changes
            public void removeTreeModelListener(TreeModelListener l) {
                // never changes
            @Override
            public String toString() {
                return name;
        public static void main(String... args) {
            new Test();
    }

  • How to display any 'String' bydefault  in a JComboBox

    Hi,
    Plz let me know how any string can be shown bydefault in a JComboBox and when the user selects this combobox then the list will appear in the combobox.
    Thanks,
    Rohit.

    Not sure I understand the question. Maybe this is what you are looking for:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.*;
    public class ComboBoxPrompt extends JFrame implements ActionListener
         JComboBox comboBox;
         public ComboBoxPrompt()
              String[] items = { "Bryan", "Nick", "Tom" };
              comboBox = new JComboBox( items );
              comboBox.setSelectedIndex(-1);
              comboBox.setRenderer( new MyRenderer() );
              getContentPane().add( comboBox, BorderLayout.NORTH );
              JButton button = new JButton("Clear Selection");
              getContentPane().add( button, BorderLayout.SOUTH );
              button.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              comboBox.setSelectedIndex(-1);
         public static void main(String[] args)
              JFrame frame = new ComboBoxPrompt();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
         class MyRenderer extends BasicComboBoxRenderer
              public Component getListCellRendererComponent(
                   JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
                   super.getListCellRendererComponent(list,
                        value, index, isSelected, cellHasFocus);
                   if (value == null)
                        setText("Select Person");
                   return this;
    }

  • Setting a default selection for a JComboBox

    Hi
    I am using a JComboBox how can I create a default selection for the combobox. If the user does not make any selection from the combo box I want them to use a default.
    --kirk123

    How about comboBox.setSelectedIndex(0) ? That will set the default selected.

  • AutoComplete JComboBox As JTable cell editor

    Hello, when I try to use AutoComplete JComboBox as my JTable cell editor, I facing the following problem
    1) Exception thrown when show pop up. - Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    2) Unable to capture enter key event.
    Here is my complete working code. With the same JComboBox class, I face no problem in adding it at JFrame. But when using it as JTable cell editor, I will have the mentioned problem.
    Any advice? Thanks
    import javax.swing.*;
    import javax.swing.JTable.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    * @author  yccheok
    public class NewJFrame extends javax.swing.JFrame {
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
                    /* Combo Box Added In JFrame. Work as expected. */
                    final JComboBox comboBox = new JComboBox();
                    comboBox.addItem("Snowboarding");
                    comboBox.addItem("Rowing");
                    comboBox.addItem("Chasing toddlers");   
                    comboBox.setEditable(true);
                    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
                       public void keyReleased(KeyEvent e) {
                           if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                               System.out.println("is enter");
                               return;
                           System.out.println("typed");
                           comboBox.setSelectedIndex(0);
                           comboBox.showPopup();
                    getContentPane().add(comboBox, java.awt.BorderLayout.SOUTH);
        public JTable getMyTable() {
            return new JTable() {
                 Combo Box Added In JTable as cell editor. Didn't work as expected:
                 1. Exception thrown when show pop up.
                 2. Unable to capture enter key event.
                public TableCellEditor getCellEditor(int row, int column) {
                    final JComboBox comboBox = new JComboBox();
                    comboBox.addItem("Snowboarding");
                    comboBox.addItem("Rowing");
                    comboBox.addItem("Chasing toddlers");   
                    comboBox.setEditable(true);
                    comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
                       public void keyReleased(KeyEvent e) {
                           if(e.getKeyCode() == KeyEvent.VK_ENTER) {
                               System.out.println("is enter");
                               return;
                           System.out.println("typed");
                           comboBox.setSelectedIndex(0);
                           comboBox.showPopup();
                    return new DefaultCellEditor(comboBox);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = getMyTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane1.setViewportView(jTable1);
            getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
            pack();
        }// </editor-fold>                       
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration                  
    }

    You need to create a custom CellEditor which will prevent these problems from occurring. The explanation behind the problem and source code for the new editor can be found at Thomas Bierhance's site http://www.orbital-computer.de/JComboBox/. The description of the problem and the workaround are at the bottom of the page.

  • JDialog stores what values are there after closing in JTextfield or JCombo.

    Hii,
    I have a problem with JDialog in which JTextField & JComboBox are there,Problem is After closing JDialog by a button "CLOSE" on it ,or by "X" on top-rightside corner, it stores values which r there in these components ,when i reopen this JDialog without Closing my Application.
    I m using dispose() method for that on CLOSE Button's Action Performed Event but i don't get what i want exactly.......Is there any other method for that CLOSE Button which not preserve those values.... ????
    Give Solution if u have......plz...
    Thanks

    add a windowListener to the dialog
    addWindowListener(new WindowAdapter(){
      public void windowClosed(WindowEvent we){
        textField.setText("");
        comboBox.setSelectedIndex(0);
    });

Maybe you are looking for