How to update 2 JCombo Boxs

前端 未结 2 696
醉梦人生
醉梦人生 2021-01-20 02:41

I have 2 Jcombo Boxs: which is combo1 and combo2

I choose combo1 and I can get information for combo2 but The problem is I can get informatiob for combo2 but it is n

2条回答
  •  佛祖请我去吃肉
    2021-01-20 03:32

    There is no need to use the updateUI() method.

    If you want to change the data in the second combo box then you should change the model (DON'T create a new combo box):

    comboBox2.setModel(...);
    

    It will repaint itself automaitcally. You can create a DefaultComboBoxModel and add the data directly to it.

    Edit:

    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    
    public class ComboBoxTwo extends JFrame implements ActionListener
    {
        private JComboBox mainComboBox;
        private JComboBox subComboBox;
        private Hashtable subItems = new Hashtable();
    
        public ComboBoxTwo()
        {
            String[] items = { "Select Item", "Color", "Shape", "Fruit" };
            mainComboBox = new JComboBox( items );
            mainComboBox.addActionListener( this );
    
            //  prevent action events from being fired when the up/down arrow keys are used
            mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
            getContentPane().add( mainComboBox, BorderLayout.WEST );
    
            //  Create sub combo box with multiple models
    
            subComboBox = new JComboBox();
            subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
            getContentPane().add( subComboBox, BorderLayout.EAST );
    
            String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
            subItems.put(items[1], subItems1);
    
            String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
            subItems.put(items[2], subItems2);
    
            String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
            subItems.put(items[3], subItems3);
    //      mainComboBox.setSelectedIndex(1);
        }
    
        public void actionPerformed(ActionEvent e)
        {
            String item = (String)mainComboBox.getSelectedItem();
            Object o = subItems.get( item );
    
            if (o == null)
            {
                subComboBox.setModel( new DefaultComboBoxModel() );
            }
            else
            {
                subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
            }
        }
    
        public static void main(String[] args)
        {
            JFrame frame = new ComboBoxTwo();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible( true );
         }
    }
    

提交回复
热议问题