Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate thru all the buttons within a swing interface?

I've created a frame with a 3x3 grid of buttons using this code...

    JFrame frame = new JFrame("my 3x3");
    JPanel panel = new JPanel();
    Container pane = frame.getContentPane();
    panel.setLayout(new GridLayout(3,3));
    panel.add(upperLeft);
    panel.add(upperCenter);
    panel.add(upperRight);
    panel.add(midLeft);
    panel.add(midCenter);
    panel.add(midRight);
    panel.add(bottomLeft);
    panel.add(bottomCenter);
    panel.add(bottomRight);
    pane.add(panel);

... with each of the upper to lower, left to right elements being JButton objects.

Later in the execution, I need a list of these buttons to iterate through to reset them, but all I have at that point is the frame. I know buried somewhere in the frame object is a list of components, perhaps layers deep, but where? Is there a straight forward way to retrieve a frame's buttons?

like image 200
dacracot Avatar asked Dec 06 '25 18:12

dacracot


1 Answers

Each swing Container has getComponents(). So, starting from the JFrame (or its getContentPane()) you can go down recursively and fetch all components.

But you can also hold a List<JButton> and fill it when you add the buttons to the panel.

like image 143
Bozho Avatar answered Dec 08 '25 06:12

Bozho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!