This applet shows that there are three radio buttons to change the label content. Here are a few notes:
1. To set up a single-choice button, you need the buttongroup class to define a group of related single-choice buttons.
2. Each single-choice button must be added to the button group, and each button must be added to the Panel independently.
3. The buttongroup object is not an organizational object and the created container is displayed. This is only a method for defining the button groups that work together and form a set of related options. The buttongroup object can automatically close the currently selected button when another button in the selected group is selected.
Actual Effect
Quoteoptions. Java
Import javax. Swing. jframe;
Public class quoteoptions {
Public static void main (string [] ARGs ){
Jframe frame = new jframe ("Quote options ");
Frame. setdefaclocloseoperation (jframe. exit_on_close );
Frame. getcontentpane (). Add (New quoteoptionspanel ());
Frame. Pack ();
Frame. setvisible (true );
}
}
Quoteoptionspanel. Java
Import javax. Swing. jradiobutton;
Import .....
Public class quoteoptionspanel extends jpanel {
Private jlabel quote;
Private jradiobutton comedy, philosophy, carpentry;
Private string comedyquote, philosophyquote, carpentryquote;
// Set a label and three radiobutton in the panel to control its content
Public quoteoptionspanel (){
Comedyquote = "I love you what you are! ";
Philosophyquote = "I think, therefore I am .";
Carpentryquote = "never, never give up .";
Quote = new jlabel (comedyquote );
Quote. setfont (new font ("Helvetica", Font. roman_baseline, 24 ));
Comedy = new jradiobutton ("Comedy", true );
Comedy. setbackground (color. Green );
Philosophy = new jradiobutton ("Philosophy ");
Philosophy. setbackground (color. Green );
Carpentry = new jradiobutton ("Carpentry ");
Carpentry. setbackground (color. Green );
Buttongroup group = new buttongroup ();
Group. Add (comedy );
Group. Add (Philosophy );
Group. Add (carpentry );
Quotelistener listener = new quotelistener ();
Comedy. addactionlistener (listener );
Philosophy. addactionlistener (listener );
Carpentry. addactionlistener (listener );
Add (quote );
Add (comedy );
Add (Philosophy );
Add (carpentry );
Setbackground (color. Green );
Setpreferredsize (New Dimensions (300,100 ));
}
// Listener for all radio buttons
Private class quotelistener implements actionlistener {
// Set the TAG content based on the single-choice button.
Public void actionreceivmed (actionevent e ){
Object source = E. getsource ();
If (Source = comedy)
Quote. settext (comedyquote );
Else
If (Source = philosophy)
Quote. settext (philosophyquote );
Else
Quote. settext (carpentryquote );
}
}