adding ButtonGroup to Box-layout object
-
27-10-2019 - |
Question
When I try to put ButtonGroup
object to my Box
object, compiler returns the following error:
no method for such a type
Please help me, how can I add my ButtonGroup
into Horizontal Box?
Solution
Something like this:
ButtonGroup bg; // your button group
Box box; // your box
// Create a panel to group the buttons.
JPanel panel = new JPanel();
// Add all of the buttons in the group to the panel.
for (Enumeration<AbstractButton> en = buttonGroup.getElements(); en.hasMoreElements();) {
AbstractButton b = en.nextElement();
panel.add(b);
}
// Add the panel to the box.
box.add(panel):
OTHER TIPS
The ButtonGroup extends Object; it is not a Component. So it is not explicitly added to a Container or Component. Rather, it groups AbstractButton instances.
Here is the example code from the Java documentation.
One advantage of not making ButtonGroup a Component (and probably the reason for implementing it this way) is that you can have AbstractButton instances on different Components be member of the same ButtonGroup.
Here is some sample code to demonstrate it, using a BoxLayout.
JPanel mainPanel = new JPanel();
mainPanel.setLayout ( new BoxLayout( mainPanel, BoxLayout.PAGE_AXIS ) );
ButtonGroup group = new ButtonGroup( );
JButton dogButton = new JButton("dog");
group.add( dogButton );
JPanel dogPanel = new JPanel( );
dogPanel.add( dogButton );
mainPanel.add( dogPanel );
JButton catButton = new JButton("cat");
group.add( catButton );
JPanel catPanel = new JPanel();
catPanel.add( catButton );
mainPanel.add( catPanel );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow