This program displays two check boxes and one label. By changing the status of the check box, you can change the text format on the label to show the font in bold, italic, or bold italic.
The GUI Design in the styleoptions program is included in the styleoptionspanel class. The check box is represented by the jcheckbox class. When the check box changes from one status to another, the itemlistener event is generated. The itemlistener Interface contains a single method itemstatechanged.
The font class is also used in the program. A font object consists of a font name, a font style, and a font size.
When the status of a check box is changed, the itemstatechanged method of the listener determines each check box in turn. This method returns a Boolean value.
Actual Effect
Styleoptions. Java
Import javax. Swing. jframe;
Public class styleoptions {
Public static void main (string [] ARGs ){
Jframe frame = new jframe ("style options ");
Frame. setdefaclocloseoperation (jframe. exit_on_close );
Frame. getcontentpane (). Add (New styleoptionspanel ());
Frame. Pack ();
Frame. setvisible (true );
}
}
Styleoptionspanel. Java
Package jcheckbox;
Import java. AWT. color;
Import java. AWT. dimension;
Import java. AWT. Font;
Import java. AWT. event. itemevent;
Import java. AWT. event. itemlistener;
Import javax. Swing. jcheckbox;
Import javax. Swing. jlabel;
Import javax. Swing. jpanel;
Public class styleoptionspanel extends jpanel {
Private jlabel saying;
Private jcheckbox bold, italic;
Public styleoptionspanel (){
Saying = new jlabel ("say it with style ");
Saying. setfont (new font ("Helvetica", Font. Plain, 36 ));
Bold = new jcheckbox ("bold ");
Bold. setbackground (color. Green );
Italic = new jcheckbox ("italic ");
Italic. setbackground (color. Green );
Stylelistener listener = new stylelistener ();
Bold. additemlistener (listener );
Italic. additemlistener (listener );
Add (saying );
Add (BOLD );
Add (italic );
Setbackground (color. Green );
Setpreferredsize (New Dimensions (300,100 ));
}
Public class stylelistener implements itemlistener {
Public void itemstatechanged (itemevent arg0 ){
Int style = font. Plain;
If (bold. isselected ())
Style = font. Bold;
If (italic. isselected ())
Style = font. italic;
Saying. setfont (new font ("Helvetica", style, 36 ));
}
}
}
There is a defect here, that is, it cannot display bold italics at the same time. If someone knows it, please tell me, I am grateful.