How to make a set of jbuttons invisible in java

10,782

Solution 1

The better solution is to have your buttons in an array or List, but if you can't do that, you can walk the immediate container (JPanel) looking for all the components that are instances of JButton

for (Component child : getComponents){
    if (child instanceof JButton) {
        ((JButton)child).setVisible(false);
    }
}

This is a little heavy handed so be careful

Solution 2

Put all your UI components (JButton) in a collection, and create a utility method that iterates over them and set the visible state.

Share:
10,782

Related videos on Youtube

Adesh
Author by

Adesh

Updated on September 16, 2022

Comments

  • Adesh
    Adesh over 1 year

    Apart from using button.setVisible(false), is there an easy way to set a set of jButtons to invisible and visible again?

    The algorithm is as follows - when the user clicks the checkout button, a set of payment buttons(denomination buttons are displayed). Trying to research if there is an easier way to accomplish this.

    • MadProgrammer
      MadProgrammer over 11 years
      How are they defined? In an array? List? or just on a container?
    • Adesh
      Adesh over 11 years
      Hi - They are just on the jpanel, not sure if that is what you meant by container. New to java, still have a lot to learn
    • FThompson
      FThompson over 11 years
      Why do you need an alternative to button.setVisible(..)?
    • pickypg
      pickypg over 11 years
      Hide the JPanel containing all of the JButtons, assuming that's all that it includes.