It sounds like you're working on a data driven Q&A program. While the approach shown is technically possible by recursively traversing the array returned from the container's getComponents()
method, the result confuses the containment & inheritance hierarchies; it also scales poorly.
Instead, separate the model (strings, selection) and view (labels, buttons), as suggested here. Let the view listen to its model using one of the notification approaches shown. In this way, each instance of the view knows its own buttons and which button is selected. Almost any of the standard Swing components is a good example of this separable model architecture.
Addendum: While I'm reluctant to endorse the implicit design limitation, here's an expedient approach.
In PanelWithRadioButton
, add a reference to panelWithTwoLabels
as a client property:
rButton.putClientProperty("labels", panelWithTwoLabels);
In actionPerformed()
, use the property to retrieve the panelWithTwoLabels
:
PanelWithTwoLabels panelWithLabels =
(PanelWithTwoLabels) btn.getClientProperty("labels");