Credits

Thursday, September 9, 2010

Java's Checkbox Component and Events

To add aesthetics and ease in data entry, check box is also used for pre - determined constants like Gender ( only options Female and Male are valid) or Civil Status (like Single, Married, Widow, Separated, Head of the Family)

To make use of a check box, you can have your constructor as:

JCheckbox object = new JCheckbox (String); 

If this check box is selected, you can use an event method to respond to this selection; a method  ItemStateChanged   shall be performed.

The program below illustrates this point.


[+/-] show/hide


/* sample use of JCheckbox with Item event */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JCheckBoxEvent extends JFrame implements ItemListener{

Container con = getContentPane();
JCheckBox bold = new JCheckBox("Bold");
JCheckBox italic = new JCheckBox("Italic");
JTextField result = new JTextField("",25);


//constructor for JCheckBoxEvent

public JCheckBoxEvent()
{ super("JCheckBox Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
con.setLayout(new GridLayout(0,1));
con.add(bold);
con.add(italic);
con.add(result);

//adding an item listener
bold.addItemListener(this);
italic.addItemListener(this);
result.setEditable(false);

setContentPane(con);


}

public void itemStateChanged(ItemEvent e){
Font ShowFont;
String text;
int style;

text = "12 point";
style =0;

Object source = e.getSource();

if (source==bold){
int select = e.getStateChange();
if(select == ItemEvent.SELECTED){
style=style|Font.BOLD;
text +=" boldface";
}
else text +=" regular weight";
}
else if (source==italic){
int select = e.getStateChange();
if(select == ItemEvent.SELECTED){
style=style|Font.ITALIC;
text +=" italic";
}
else text +=" roman";
}

text += " font";
ShowFont = new Font("Arial",style,12);
result.setFont(ShowFont);
result.setText(text);

}


public static void main (String[] args)
{ JFrame aFrame = new JCheckBoxEvent();
aFrame.setSize(250,150);
aFrame.setVisible(true);
}}

AddThis