power_settings_new
I have a scenario where I have many combo boxes, more than 20. I do not want to write code to clear each comobox and set values to each. Rather, I need to write functions which can take all comoboxes, iterate through those and remove all values. Also, I have a list of values which I should be able to set. List of items is same across all comoboxes.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.

2 Answers

by (171 points)
0 votes
Try below line of code.

 

private void clearAllComoboxes(JFrame frame){
        Component[] components = frame.getComponents();
        for(Component component : components){
            if(component instanceof JComboBox){
                ((JComboBox) component).removeAllItems();
            }
        }
    }
    private void setValuesToComoboxes(JFrame frame, Set<String> values){
        Component[] components = frame.getComponents();
        for(Component component : components){
            if(component instanceof JComboBox){
                for(String value : values){
                    ((JComboBox) component).addItem(value);
                }
            }
        }
    }
by (171 points)
0 votes

You need to use getContentPane()

 

private void clearAllComoboxes(JFrame frame){
        Component[] components = frame.getContentPane().getComponents();
        for(Component component : components){
            if(component instanceof JComboBox){
                ((JComboBox) component).removeAllItems();
            }
        }
    }
    
    private void setValuesToComoboxes(JFrame frame, String[] values){
        Component[] components = frame.getContentPane().getComponents();
        for(Component component : components){
            if(component instanceof JComboBox){
                for(String value : values){
                    ((JComboBox) component).addItem(value);
                }
            }
        }
    }

add
...