Checkout our demo site to practice selenium https://magento.softwaretestingboard.com/

1 like 0 dislike
278 views
in Programming by
retagged by
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.

2 Answers

0 like 0 dislike
by The go-to Tester (181 points)
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);
                }
            }
        }
    }
0 like 0 dislike
by The go-to Tester (181 points)

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);
                }
            }
        }
    }


This site is for software testing professionals, where you can ask all your questions and get answers from 1300+ masters of the profession. Click here to submit yours now!

1.4k questions

1.6k answers

866 comments

1.9k users

...