下面是一个Application程序,其功能是在框架中放置了四个单选框和一个标签,选择不同单选框将在标签上显示不同的提示信息。
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
importjavax.swing.event.*;
publicclassRadioButtonExample
{
publicstaticvoidmain(String[]args)
{
RadioButtonFrameframe=newRadioButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT-ON-CLOSE);
frame.show();
}
}
classRadioButtonFrameextendsJFrame
{
publicRadioButtonFrame()
{
setTitle(″RadioButtonExample″);
setSize(WIDTH,HEIGHT);
ContainercontentPane=getContentPane();
myLabel=newJLabel(″提示标签″,JLabel.CENTER);
contentPane.add(myLabel,BorderLayout.CENTER);
radionPanel=newJPanel();
myButtonGroup=newButton();
addRadioButton(″EAST″,true,″EAST″);
addRadioButton(″SOUTH″,false,″SOUTH″);
addRadioButton(″WEST″,false,″WEST″);
addRadioButton(″NORTH″,false,″NORTH″);
contentPane.add(radioPanel,BorderLayout.SOUTH);
}
publicvoidaddRadioButton(Stringname,booleandefaultRadio,Stringshow)
{
finalStringshowLabel=show;
JRadioButtonbutton=newJRadioButton(name,defaultRadio);
myButtonGroup.add(button);
radioPanel.add(button);
button.addActionListener(newActionListener()
{
publicvoidactionPerformed(ActionEventevt)
{
myLabel.Text(″你选择了:″+showLabel);
}
});
}
publicstaticfinalintWIDTH=300;
publicstaticfinalintHEIGHT=140;
privateJLabelmyLabel;
privateButtonGroupmyButtonGroup;
privateJPanelradioPanel;
}