Search code examples
javajframejpaneljcomboboxjcomponent

Reset ComboBox with new values


How could I reload the JComboBox object with new values? Should I re-add the JComboBox object to the Panel again in order to see the new values displayed, P.S. I eliminated the method that will add new values to the stack, and I hope to reach my target after the "????" comment, as you can see ComPort is the array that I wish to use its new values in the combobox>

  <i>
    public class Test {
        static String [] ComPort={"No Ports Available"};
        static Stack ComPortList=new Stack();
        static JPanel Pan=new JPanel();
        static JComboBox Com=null;
        static JFrame Fra=new JFrame();
        public Test()
        {
            Com=new JComboBox(ComPort);
            Fra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Fra.setSize(750, 750);
            Pan.add(Com);
            Pan.setPreferredSize(new Dimension(500,500));
            Fra.setVisible(true);
            Fra.setResizable(false);
            Fra.add(Pan);
        }
        public static void main(String args[])
        {
            new Test();
            AvailablePort();
            for(int i=0;i<100;i++)
                if(ComPortList.isEmpty())
                    break;
                else
                    ComPort[i]=(String) ComPortList.pop();
            Com=new JComboBox(ComPort);
            //????
        }
    </i>

Solution

  • You can get the ComboBoxModel and use it to remove all existing items and add the new ones, or it might be easier just to create a new JComboBox, passing the new items to its constructor.