문제

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?

도움이 되었습니까?

해결책

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):

다른 팁

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 );
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top