Swing radio button
Last Update:2018-12-03
Source: Internet
Author: User
Package Two ;/*
Java swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O 'Reilly
*/
// Simplebuttongroupexample. Java
// A buttongroup voting booth.
// Import java. AWT. container;
Import java. AWT. gridlayout;
Import java. AWT. event. actionevent;
Import java. AWT. event. actionlistener;
Import java. AWT. event. itemevent;
Import java. AWT. event. itemlistener; import javax. Swing. abstractbutton;
Import javax. Swing. buttongroup;
Import javax. Swing. jframe;
Import javax. Swing. jlabel;
Import javax. Swing. jradiobutton; public class simplebuttongroupexample {public static void main (string [] ARGs ){
// Some choices
Jradiobutton choice1, choice2, choice3;
Choice1 = new jradiobutton ("Bach: Well Tempered clavier, book I ");
Choice1.setactioncommand ("bach1 ");
Choice2 = new jradiobutton ("Bach: Well Tempered clavier, Book II ");
Choice2.setactioncommand ("bach2 ");
Choice3 = new jradiobutton ("Shostakovich: 24 preludes and fugues ");
Choice3.setactioncommand ("Shostakovich"); // a group, to ensure that we only vote for one.
Final buttongroup group = new buttongroup ();
Group. Add (choice1 );
Group. Add (choice2 );
Group. Add (choice3); // a simple actionlistener, showing each selection using the buttonmodel
Class voteactionlistener implements actionlistener {
Public void actionreceivmed (actionevent eV ){
String choice = group. getselection (). getactioncommand ();
System. Out. println ("action choice selected:" + choice );
}
} // A simple itemlistener, showing each selection and deselection
Class voteitemlistener implements itemlistener {
Public void itemstatechanged (itemevent eV ){
Boolean selected = (EV. getstatechange () = itemevent. Selected );
Using actbutton button = (using actbutton) eV. getitemselectable ();
System. Out. println ("item choice selected:" + selected
+ ", Selection:" + button. getactioncommand ());
}
} // Add listeners to each button
Actionlistener alisten = new voteactionlistener ();
Choice1.addactionlistener (alisten );
Choice2.addactionlistener (alisten );
Choice3.addactionlistener (alisten); itemlistener ilisten = new voteitemlistener ();
Choice1.additemlistener (ilisten );
Choice2.additemlistener (ilisten );
Choice3.additemlistener (ilisten); // throw everything together
Jframe frame = new jframe ();
Frame. setdefaclocloseoperation (jframe. exit_on_close );
Container c = frame. getcontentpane ();
C. setlayout (New gridlayout (0, 1 ));
C. Add (New jlabel ("vote for your favorite prelude & fugue cycle "));
C. Add (choice1 );
C. Add (choice2 );
C. Add (choice3 );
Frame. Pack ();
Frame. setvisible (true );
}
}