Following is an exclusive program on JCheckBox. The text font in a text field is changed as per the JCheckBox selected by the user. Four JCheckBox objects are created for font name, font style, font size and to close the JFrame. The counterpart of JCheckBox in java.awt is Checkbox.
Example on JCheckBox
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JCheckBoxDemo extends JFrame implements ItemListener
{
JTextField tf ;
JCheckBox namebox, boldbox, italicbox, closebox ;
public JCheckBoxDemo()
{
Container c = getContentPane(); // default BorderLayout is used
// create the text field
tf = new JTextField("way2java",30);
tf.setBackground(Color.cyan);
c.add(tf);
// create JCheckBox objects
namebox = new JCheckBox("Monospaced");
c.add(namebox, "North");
boldbox = new JCheckBox("Bold"); // Bold will be displayed
c.add(boldbox, "West"); // besides the checkbox
italicbox = new JCheckBox("Italic");
c.add(italicbox, "East");
closebox = new JCheckBox("Exit"); // this checkbox when selected, closes the window
closebox.setForeground(Color.red);
c.add(closebox, "South");
// register each checkbox with ItemListener
namebox.addItemListener(this);
boldbox.addItemListener(this);
italicbox.addItemListener(this);
closebox.addItemListener(this);
setTitle("Learning JButton");
setSize(400,200);
setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
String fontname = ""; // some compilers will raise error if local variables
int b = 0, i = 0 ; // are not initialized
if(namebox.isSelected())
fontname = "Monospaced";
else
fontname = "Serif";
if(boldbox.isSelected())
b = Font.BOLD;
else
b = Font.PLAIN;
if(italicbox.isSelected())
i = Font.ITALIC;
else
i = Font.PLAIN;
if(closebox.isSelected())
System.exit(0);
Font f = new Font(fontname, b + i , 25); // create a Font object with the user selection of checkboxes
tf.setFont(f); // setting a font to the text in the textfield
}
public static void main( String args[ ] )
{
new JCheckBoxDemo();
}
}
b = Font.BOLD;
You know in AWT Font, the font style comprising Plain, Bold and Italic were declared as static final variables in Font class.