More Swing componenets

This is the last note on swing componenets.
Here are steps to learn how to use different swing components
  1. Find out the related java tutorial in A Visual Index to the Swing Components
  2. Find out what properties can be set/get
  3. Find out what kind of user interaction exists for the components
Example : JTextField:
  1. Read this java tutorial How to Use Text Fields
  2. Read the java document JTextField
  3. find out set/get method. Example, setText, getText
  4. user presses return after input text (ActionListener)

TextFieldTest.java

You can get the program here.
This is the output of the program
textfielda.gif
The output.
textfieldb.gif Press the return and the text will be copied to another text field
   1:import java.awt.*;
   2:import javax.swing.*;
   3:import java.awt.event.*;
   4:
   5:public class TextFieldTest extends JFrame {
   6:    private JTextField copyFrom;
   7:    private JTextField copyTo;
   8:    private JLabel label = new JLabel("Press return to copy the text");
   9:    private JButton clearButton = new JButton("Clear all the text fields");
  10:    public TextFieldTest() {
  11:        getContentPane().setLayout(new GridLayout(4,1));
  12:        copyFrom = new JTextField("Type here");
  13:        copyTo = new JTextField();
  14:        getContentPane().add(copyFrom);
  15:        getContentPane().add(label);
  16:        getContentPane().add(copyTo);
  17:        getContentPane().add(clearButton);
  18:        
  19:        copyFrom.addActionListener(new TextListener());
  20:        clearButton.addActionListener(new ButtonListener());
  21:    }
  22:    
  23:    class ButtonListener implements ActionListener {
  24:        public void actionPerformed(ActionEvent e) {
  25:            // clear the text field
  26:            copyFrom.setText("");
  27:            copyTo.setText("");
  28:        }
  29:    }
  30:    
  31:    class TextListener implements ActionListener {
  32:        public void actionPerformed(ActionEvent e) {
  33:            // get the text form the text field and copy to the other
  34:            String text = copyFrom.getText();
  35:            copyTo.setText(text);
  36:        }
  37:    }
  38:    
  39:      public static void main(String[] args) {
  40:        TextFieldTest f = new TextFieldTest();
  41:        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  42:        f.pack();
  43:        f.setVisible(true);
  44:    }
  45:}
  46:        

Explanation


JTextField

The API for using text fields and password fields falls into these categories:

Setting or Getting the Field's Contents
Method or Constructor Purpose
JTextField()
JTextField(String)
JTextField(String, int)
JTextField(int)
Create a text field. When present, the int argument specifies the desired width in columns. The String argument contains the field's initial text.
JPasswordField()
JPasswordField(String)
JPasswordField(String, int)
JPasswordField(int)
Create a password field. When present, the int argument specifies the desired width in columns. The String argument contains the field's initial text.
void setText(String)
String getText()
Set or get the text displayed by the text field. Note that getText is deprecated for password fields in Swing 1.0.3 and higher releases.
char[] getPassword()
(in JPasswordField)
Set or get the text displayed by the text field. Note that this method does not exist in Swing 1.0.3 and lower releases.

Fine Tuning the Field's Appearance
Method or Constructor Purpose
void setEditable(boolean)
boolean isEditable()
Set or get whether the user can edit the text in the text field.
void setColumns(int);
int getColumns()
Set or get the number of columns displayed by the text field. This is really just a hint for computing the field's preferred width.
int getColumnWidth() Get the width of the text field's columns. This value is established implicitly by the font.
void setHorizontalAlignment(int);
int getHorizontalAlignment()
Set or get how the text is aligned horizontally within its area. You can use JTextField.LEFT, JTextField.CENTER, and JTextField.RIGHT for arguments.
void setEchoChar(char)
char getEchoChar()

(in JPasswordField)
Set or get the echo character -- the character displayed instead of the actual characters typed by the user.

Implementing the Field's Functionality
Method or Constructor Purpose
void addActionListener(ActionListener)
void removeActionListener(ActionListener)
Add or remove an action listener.

PasswordTest.java

You can get the program here.

Wrong password

Correct password
   1:import java.awt.*;
   2:import javax.swing.*;
   3:import java.awt.event.*;
   4:
   5:public class PasswordFieldTest extends JFrame implements ActionListener {
   6:    private JLabel label = new JLabel("Enter password: ");
   7:    private JLabel display = new JLabel();
   8:    private String password = "charlespic";
   9:    // the password field has 10 characters width
  10:    private JPasswordField passwordField= new JPasswordField(10); 
  11:    public PasswordFieldTest() {
  12:        passwordField.setEchoChar('X');
  13:        passwordField.addActionListener(this);
  14:        
  15:        display.setPreferredSize(new Dimension(100,18));
  16:        
  17:        getContentPane().add(label);
  18:        getContentPane().add(passwordField, BorderLayout.EAST);
  19:        getContentPane().add(display, BorderLayout.SOUTH);
  20:    }
  21:    
  22:    public static void main(String[] args) {
  23:        PasswordFieldTest f = new PasswordFieldTest();
  24:        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  25:        f.pack();
  26:        f.setVisible(true);
  27:    }
  28:    
  29:    public void actionPerformed(ActionEvent e) {
  30:        char[] array = passwordField.getPassword();
  31:        if(isPasswordCorrect(array)) {
  32:            display.setText("Password is correct.");
  33:        } else {
  34:            display.setText("Password is incorrect.");
  35:        }
  36:    }
  37:    
  38:    public boolean isPasswordCorrect(char[] array) {
  39:        char[] passwordArray = password.toCharArray();
  40:        if(array.length != passwordArray.length) {
  41:            return false;
  42:        } 
  43:        
  44:        for(int i = 0; i < passwordArray.length; i++) {
  45:            if(passwordArray[i] != array[i]) {
  46:                return false;
  47:            }
  48:        }
  49:        return true;
  50:    }
  51:}         

Explanation

Summation.java

You can get the program here.

Press return after you enter the number. The new sum shows up.

   1:import java.awt.*;
   2:import javax.swing.*;
   3:import java.awt.event.*;
   4:
   5:public class Summation extends JFrame {
   6:    JTextField textField = new JTextField(10);
   7:    JButton button = new JButton("Restart");
   8:    JLabel result = new JLabel("Sum: 0");
   9:    int sum = 0;
  10:    public Summation() {
  11:        getContentPane().add(textField);
  12:        getContentPane().add(button, BorderLayout.EAST);
  13:        getContentPane().add(result, BorderLayout.SOUTH);
  14:        textField.addActionListener(new TextListener());
  15:        button.addActionListener(new ButtonListener());
  16:    }
  17:    
  18:   public static void main(String[] args) {
  19:        Summation f = new Summation();
  20:        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  21:        f.pack();
  22:        f.setVisible(true);
  23:    }
  24:    
  25:    class TextListener implements ActionListener {
  26:        public void actionPerformed(ActionEvent e) {
  27:            // get the text
  28:            String text = textField.getText();
  29:            // change to integer format
  30:            int change = Integer.parseInt(text);
  31:            // add to the sum and display it
  32:            sum+=change;
  33:            result.setText("Sum: " + sum);
  34:            textField.setText("");
  35:        }
  36:    }
  37:    
  38:    class ButtonListener implements ActionListener {
  39:        public void actionPerformed(ActionEvent e) {
  40:            textField.setText("");
  41:            sum = 0;
  42:            result.setText("Sum: " + sum);
  43:        }
  44:    }
  45:}  

Explanation

Line 30 : change the string to integer by Integer.parseInt(String).

Question

What happens if the string is not in number format, for example, if it is "abc"?

Answer

A runtime error occurs.

Summation2.java

You can get the program here.
   1:import java.awt.*;
   2:import javax.swing.*;
   3:import java.awt.event.*;
   4:
   5:public class Summation2 extends JFrame {
   6:    JTextField textField = new JTextField(10);
   7:    JButton button = new JButton("Restart");
   8:    JLabel result = new JLabel("Sum: 0");
   9:    int sum = 0;
  10:    public Summation2() {
  11:        getContentPane().add(textField);
  12:        getContentPane().add(button, BorderLayout.EAST);
  13:        getContentPane().add(result, BorderLayout.SOUTH);
  14:        textField.addActionListener(new TextListener());
  15:        button.addActionListener(new ButtonListener());
  16:    }
  17:    
  18:   public static void main(String[] args) {
  19:        Summation2 f = new Summation2();
  20:        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  21:        f.pack();
  22:        f.setVisible(true);
  23:    }
  24:    
  25:    class TextListener implements ActionListener {
  26:        public void actionPerformed(ActionEvent e) {
  27:            // get the text
  28:            String text = textField.getText();
  29:            // change to integer format
  30:            int change = 0;
  31:            // try and catch 
  32:            try {
  33:               change = Integer.parseInt(text);
  34:            } catch (Exception ex) {
  35:                // if it is not a number
  36:                textField.setText("");
  37:                return;
  38:            }
  39:            // add to the sum and display it
  40:            sum+=change;
  41:            result.setText("Sum: " + sum);
  42:            textField.setText("");
  43:        }
  44:    }
  45:    
  46:    class ButtonListener implements ActionListener {
  47:        public void actionPerformed(ActionEvent e) {
  48:            textField.setText("");
  49:            sum = 0;
  50:            result.setText("Sum: " + sum);
  51:        }
  52:    }
  53:}

Explanation

: Line 32-38: catch exception.

JCheckBox

Here is how JCheckBox looks like :
checkboxdemo.gif
JCheckBox is a kind of buttons. When you click on it, you check or uncheck the button. The way to use it is not too much different from JButton.
The following tables list the commonly used API.

Setting or Getting the JCheckBox's Contents
Method or Constructor Purpose
JCheckBox(String)
JCheckBox(String, boolean)
JCheckBox(Icon)
JCheckBox(Icon, boolean)
JCheckBox(String, Icon)
JCheckBox(String, Icon, boolean)
JCheckBox()
Create a JCheckBox instance. The string argument specifies the text, if any, that the check box should display. Similarly, the Icon argument specifies the image that should be used instead of the look and feel's default check box image. Specifying the boolean argument as true initializes the check box to be selected. If the boolean argument is absent or false, then the check box is initially unselected.
void setText(String)
String getText()
Set or get the text displayed by the button.
void setIcon(Icon)
Icon getIcon()
Set or get the image displayed by the button when the button isn't selected or pressed.
void setDisabledIcon(Icon)
Icon getDisabledIcon()
Set or get the image displayed by the button when it's disabled. If you don't specify a disabled image, then the look and feel creates one by manipulating the default image.
void setPressedIcon(Icon)
Icon getPressedIcon()
Set or get the image displayed by the button when it's being pressed.
void setSelectedIcon(Icon)
Icon getSelectedIcon()
void setDisabledSelectedIcon(Icon)
Icon getDisabledSelectedIcon()
Set or get the image displayed by the button when it's selected. If you don't specify a disabled selected image, then the look and feel creates one by manipulating the selected image.
setRolloverEnabled(boolean)
boolean getRolloverEnabled()
void setRolloverIcon(Icon)
Icon getRolloverIcon()
void setRolloverSelectedIcon(Icon)
Icon getRolloverSelectedIcon()
Use setRolloverEnabled(true) and setRolloverIcon(someIcon) to make the button display the specified icon when the cursor passes over it.

Fine Tuning the JCheckBox's Appearance
Method or Constructor Purpose
void setHorizontalAlignment(int)
void setVerticalAlignment(int)
int getHorizontalAlignment()
int getVerticalAlignment()
Set or get where in the button its contents should be placed. The AbstractButton class allows any one of the following values for horizontal alignment: LEFT, CENTER (the default), and RIGHT. For vertical alignment: TOP, CENTER (the default), and BOTTOM.
void setHorizontalTextPosition(int)
void setVerticalTextPosition(int)
int getHorizontalTextPosition()
int getVerticalTextPosition()
Set or get where the button's text should be placed, relative to the button's image. The AbstractButton class allows any one of the following values for horizontal position: LEFT, CENTER, and RIGHT (the default). For vertical position: TOP, CENTER (the default), and BOTTOM.

Implementing the JCheckBox's Functionality
Method or Constructor Purpose
void setActionCommand(String)
String getActionCommand(void)
Set or get the name of the action performed by the button.
void addActionListener(ActionListener)
ActionListener removeActionListener()
Add or remove an object that listens for action events fired by the button.
void addItemListener(ItemListener)
ItemListener removeItemListener()
Add or remove an object that listens for item events fired by the button.
void setSelected(boolean)
boolean isSelected()
Set or get whether the button is selected. Makes sense only for buttons that have on/off state, such as check boxes.

States

In addtion to the states that a button normally has (icon, background, foreground, rolloverIcon,.... ), there are some addtional states of JCheckBox :
Let's take a look at our first example.

CheckBoxTest.java

You can get the program here.
Here is the look of the program after I clicked on computer and printer checkboxes.
And the program has no interation with the user yet.
checkboxtest.gif
   1:import java.awt.*;
   2:import javax.swing.*;
   3:import java.awt.event.*;
   4:// this is a program with a label and checkboxes. 
   5:// it has no interaction with the user
   6:
   7:public class CheckBoxTest extends JFrame {
   8:    // the label displays the total price
   9:    private JLabel display = new JLabel("The total price is : $0");
  10:    // a list of JCheckBox, with the the electronic components on it 
  11:    // and also the price
  12:    private JCheckBox computer = new JCheckBox("Computer: $900");
  13:    private JCheckBox dvd = new JCheckBox("DVD: $250");
  14:    private JCheckBox printer = new JCheckBox("Printer: $70");
  15:    private JCheckBox monitor = new JCheckBox("Monitor: $299");
  16:    // the panel contains the checkboxes
  17:    private JPanel pricePanel = new JPanel(new GridLayout(1,0));
  18:    
  19:    // constructor
  20:    public CheckBoxTest() {
  21:        getContentPane().add(display);
  22:        // add the components to the pricePanel
  23:        pricePanel.add(computer);
  24:        pricePanel.add(dvd);
  25:        pricePanel.add(printer);
  26:        pricePanel.add(monitor);
  27:        getContentPane().add(pricePanel, BorderLayout.SOUTH);
  28:    }
  29:    
  30:    public static void main(String[] args) {
  31:        CheckBoxTest f = new CheckBoxTest();
  32:        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  33:        f.pack();
  34:        f.setVisible(true);
  35:    }
  36:}   
Constructor
The constructors are very similar to the constructors for JButton.
But we have few more constructors : JCheckBox(String, boolean), JCheckBox(Icon, boolean), JCheckBox(String, Icon, boolean) . If the boolean is set to be true, then the JCheckBox is set to be selected(checked), else it is unselected (unchecked). The default is unselected.
Highlight
There is nothing special about the program. We create 4 checkboxes from line 12-line 15.

CheckBoxTest2.java

You can get the program here.
Here is the output of the program after you click on computer and monitor checkboxes.
You check the boxes and the total price will show up.
checkboxtest2.gif
   1:import java.awt.*;
   2:import javax.swing.*;
   3:import java.awt.event.*;
   4:// click on the checkbox
   5:// the total price will show up
   6:public class CheckBoxTest2 extends JFrame implements ActionListener {
   7:    // the label the display the price
   8:    private JLabel display = new JLabel("The total price is $0");
   9:    // a list of JCheckBox, with the the electronic on it 
  10:    // with the price
  11:    private JCheckBox computer = new JCheckBox("Computer: $900");    
  12:    private JCheckBox dvd = new JCheckBox("DVD: $250");
  13:    private JCheckBox printer = new JCheckBox("Printer: $70");  
  14:    private JCheckBox monitor = new JCheckBox("Monitor: $299");   
  15:    private JPanel pricePanel = new JPanel(new GridLayout(1,0));
  16:    private int price = 0;
  17:    
  18:    // constructor
  19:    public CheckBoxTest2() {
  20:        getContentPane().add(display);
  21:        // add the components to pricePanel
  22:        pricePanel.add(computer);
  23:        pricePanel.add(dvd);
  24:        pricePanel.add(printer);
  25:        pricePanel.add(monitor);
  26:        
  27:        // add actionListener to all the check boxes
  28:        computer.addActionListener(this);
  29:        dvd.addActionListener(this);
  30:        printer.addActionListener(this);
  31:        monitor.addActionListener(this);
  32:        
  33:        getContentPane().add(pricePanel, BorderLayout.SOUTH);
  34:    }
  35:    
  36:    public static void main(String[] args) {
  37:        CheckBoxTest2 f = new CheckBoxTest2();
  38:        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  39:        f.pack();
  40:        f.setVisible(true);
  41:    }
  42:    
  43:    public void actionPerformed(ActionEvent e) {
  44:        // check the source first
  45:        // if the source is selected, than add to the price
  46:        // else, it is unselected, reduce from the price.
  47:        if(e.getSource() == computer) {
  48:            if(computer.isSelected()) {
  49:                price+=900;
  50:            } else {
  51:                price-=900;
  52:            }
  53:        } else if (e.getSource() == dvd) {
  54:            if(dvd.isSelected()) {
  55:                price+=250;
  56:            } else {
  57:                price-=250;
  58:            }
  59:        } else if(e.getSource() == printer) {
  60:            if(printer.isSelected()){
  61:                price+=70;
  62:            } else {
  63:                price-=70;
  64:            }
  65:        } else if(e.getSource() == monitor) {
  66:            if(monitor.isSelected()) {
  67:                price+=299;
  68:            } else {
  69:                price-=299;
  70:            }
  71:        }
  72:        // update the price
  73:        display.setText("The total price is $" + price);
  74:    }
  75:            
  76:}    
Difference
The main difference of this program and the previous program is that we create an ActionListener. And the price is updated after you click on check box.

actionPerformed
  1. check the source using e.getSource()
  2. compare the source with the JCheckBoxes: computer,dvd,printer,monitor
  3. add(or substract) the amount of the correponding JCheckBox.
e.getSource()
get the source generated the event. We compare the source with the JCheckBoxes by e.getSource() == computer etc.

checkBox.isSelected()
There are 2 useful methods in class JCheckBox : isSelected, setSelected(boolean). The meaning is obvious.

Highlight

CheckBoxTest3.java

You can get the program here.
You can get the picture after the codes . Save the pictures in images folder.
Here is the output of the program after you click on computer and monitor.
checkboxtest3.gif
   1:import java.awt.*;
   2:import javax.swing.*;
   3:import java.awt.event.*;
   4:
   5:// select the things by clicking on the picture
   6:public class CheckBoxTest3 extends JFrame implements ActionListener {
   7:    // the label the display the price
   8:    private JLabel display = new JLabel();
   9:    // a list of JCheckBox, with the the electronic names on it  
  10:    // with the price
  11:    private JCheckBox computer = new JCheckBox("Computer: $900");    
  12:    private JCheckBox dvd = new JCheckBox("DVD: $250");
  13:    private JCheckBox printer = new JCheckBox("Printer: $70");  
  14:    private JCheckBox monitor = new JCheckBox("Monitor: $299");   
  15:    private JPanel pricePanel = new JPanel(new GridLayout(2,2));
  16:    private int price = 0;
  17:    
  18:    // constructor
  19:    public CheckBoxTest3() {
  20:        display.setOpaque(true);
  21:        // set the background color
  22:        display.setBackground(Color.white);
  23:        // set the font color
  24:        display.setForeground(Color.blue.darker());
  25:        // use html file, <h1> .. </h1> set the font size 
  26:        display.setText("<html><h1>The total price is $0</h1><html>");
  27:        getContentPane().add(display);
  28:        
  29:        // add the components to pricePanel
  30:        pricePanel.add(computer);
  31:        pricePanel.add(dvd);
  32:        pricePanel.add(printer);
  33:        pricePanel.add(monitor);
  34:        
  35:        // setIcon set the icon for the checkbox
  36:        // the icon is set to a computer icon with a black cross
  37:        // setSelectedIcon set the icon when you select the checkbox
  38:        // the icon is set to a computer icon without cross
  39:        computer.addActionListener(this);
  40:        computer.setBackground(Color.white);
  41:        computer.setIcon(new ImageIcon("images/computerx.jpg"));
  42:        computer.setSelectedIcon(new ImageIcon("images/computer.jpg"));
  43:        
  44:        dvd.addActionListener(this);
  45:        dvd.setBackground(Color.white);
  46:        dvd.setIcon(new ImageIcon("images/dvdx.jpg"));
  47:        dvd.setSelectedIcon(new ImageIcon("images/dvd.jpg"));
  48:        
  49:        printer.addActionListener(this);
  50:        printer.setBackground(Color.white);
  51:        printer.setIcon(new ImageIcon("images/printerx.jpg"));
  52:        printer.setSelectedIcon(new ImageIcon("images/printer.jpg"));
  53:        
  54:        monitor.addActionListener(this);
  55:        monitor.setBackground(Color.white);
  56:        monitor.setIcon(new ImageIcon("images/monitorx.jpg"));
  57:        monitor.setSelectedIcon(new ImageIcon("images/monitor.jpg"));
  58:        
  59:        getContentPane().add(pricePanel, BorderLayout.SOUTH);
  60:    }
  61:    
  62:    public static void main(String[] args) {
  63:        CheckBoxTest3 f = new CheckBoxTest3();
  64:        f.setTitle("Bruin Computer Store");
  65:        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  66:        f.pack();
  67:        f.setVisible(true);
  68:    }
  69:    
  70:    public void actionPerformed(ActionEvent e) {
  71:        // check the source first
  72:        // if the source is selected, than add the price
  73:        // else, it is unselected, delete the price.
  74:        if(e.getSource() == computer) {
  75:            if(computer.isSelected()) {
  76:                price+=900;
  77:            } else {
  78:                price-=900;
  79:            }
  80:        } else if (e.getSource() == dvd) {
  81:            if(dvd.isSelected()) {
  82:                price+=250;
  83:            } else {
  84:                price-=250;
  85:            }
  86:        } else if(e.getSource() == printer) {
  87:            if(printer.isSelected()){
  88:                price+=70;
  89:            } else {
  90:                price-=70;
  91:            }
  92:        } else if(e.getSource() == monitor) {
  93:            if(monitor.isSelected()) {
  94:                price+=299;
  95:            } else {
  96:                price-=299;
  97:            }
  98:        }
  99:        // update the price
 100:        display.setText("<html><h1>The total price is $" + price + "</h1></html>");
 101:    }
 102:            
 103:}

Difference
The main difference between this program and the previous program is the icons.
Instead using the default icons(a square for unselected check box and a square with a kick for selected check box) we use our own pictures.
save the pictures in a folder name images
computer
computer(selected)
dvd
dvd(selected)
printer
printer(selected)
monitor
monitor(selected)
computerx
computer(unselected)
dvdx
dvd(unslected)
printerx
printer(unselected)
monitorx
monitor(unselected)

setIcon, setSelectedIcon
setIcon set the icon when it is unselected.
setSelectedIcon set the icon when it is selected.

Highlight

CheckBoxTest4.java

You can get the program here.
The program works exactly the same as the previous one.
   1:import java.awt.*;
   2:import javax.swing.*;
   3:import java.awt.event.*;
   4:public class CheckBoxTest4 extends JFrame implements ItemListener {
   5:    // the label the display the price
   6:    private JLabel display = new JLabel();
   7:    // a list of JCheckBox, with the the electronic names on it  
   8:    // with the price
   9:    private JCheckBox computer = new JCheckBox("Computer: $900");    
  10:    private JCheckBox dvd = new JCheckBox("DVD: $250");
  11:    private JCheckBox printer = new JCheckBox("Printer: $70");  
  12:    private JCheckBox monitor = new JCheckBox("Monitor: $299");   
  13:    private JPanel pricePanel = new JPanel(new GridLayout(2,2));
  14:    private int price = 0;
  15:    
  16:    // constructor
  17:    public CheckBoxTest4() {
  18:        display.setOpaque(true);
  19:        // set the background color
  20:        display.setBackground(Color.white);
  21:        // set the font color
  22:        display.setForeground(Color.blue.darker());
  23:        // use html file, <h1> .. </h1> set the font size 
  24:        display.setText("<html><h1>The total price is $0</h1><html>");
  25:        getContentPane().add(display);
  26:        
  27:        // add the components to pricePanel
  28:        pricePanel.add(computer);
  29:        pricePanel.add(dvd);
  30:        pricePanel.add(printer);
  31:        pricePanel.add(monitor);
  32:        
  33:        
  34:        // setIcon set the icon for the checkbox
  35:        // the icon is set to be a computer icon with a black cross
  36:        // setSelectedIcon set the icon when you select the checkbox
  37:        // the icon is set be a computer icon without cross
  38:        computer.addItemListener(this);
  39:        computer.setBackground(Color.white);
  40:        computer.setIcon(new ImageIcon("images/computerx.jpg"));
  41:        computer.setSelectedIcon(new ImageIcon("images/computer.jpg"));
  42:        
  43:        dvd.addItemListener(this);
  44:        dvd.setBackground(Color.white);
  45:        dvd.setIcon(new ImageIcon("images/dvdx.jpg"));
  46:        dvd.setSelectedIcon(new ImageIcon("images/dvd.jpg"));
  47:        
  48:        printer.addItemListener(this);
  49:        printer.setBackground(Color.white);
  50:        printer.setIcon(new ImageIcon("images/printerx.jpg"));
  51:        printer.setSelectedIcon(new ImageIcon("images/printer.jpg"));
  52:        
  53:        monitor.addItemListener(this);
  54:        monitor.setBackground(Color.white);
  55:        monitor.setIcon(new ImageIcon("images/monitorx.jpg"));
  56:        monitor.setSelectedIcon(new ImageIcon("images/monitor.jpg"));
  57:        
  58:        getContentPane().add(pricePanel, BorderLayout.SOUTH);
  59:    }
  60:    
  61:    public static void main(String[] args) {
  62:        CheckBoxTest4 f = new CheckBoxTest4();
  63:        f.setTitle("Bruin Computer Store");
  64:        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  65:        f.pack();
  66:        f.setVisible(true);
  67:    }
  68:    
  69:    // override the method form ItemListener
  70:    public void itemStateChanged(ItemEvent e) {
  71:        // check the source first
  72:        // find out the source and get the price change
  73:        // if the source is selected, add the price change
  74:        // if it is not selected, deducted the price change
  75:        
  76:        int change=0;
  77:        if(e.getSource() == computer) {
  78:            change = 900;
  79:        } else if (e.getSource() == dvd) {
  80:           change = 250;
  81:        } else if(e.getSource() == printer) {
  82:            change = 70;
  83:        } else if(e.getSource() == monitor) {
  84:            change =299;
  85:        }
  86:        
  87:        if(e.getStateChange() == ItemEvent.SELECTED) {
  88:          price+=change;
  89:        } else if(e.getStateChange() == ItemEvent.DESELECTED) {
  90:            price-=change;
  91:        }
  92:        display.setText("<html><h1>The total price is $" + price + "</h1></html>");
  93:    }
  94:            
  95:}

ItemListener

It corresponds to the change of the states of components (example form checked to unchecked.)
It is an interface in package java.awt.*
It has only one method public void itemStateChanged(ItemEvent e). You have to override this method when you implements ItemListener.

ItemEvent

It is a class is package java.awt.event.*.
Some useful members are:

highlight of the program


JRadioButton

Constructors

Radio Button Constructors
Constructor Purpose
JRadioButton(String)
JRadioButton(String, boolean)
JRadioButton(Icon)
JRadioButton(Icon, boolean)
JRadioButton(String, Icon)
JRadioButton(String, Icon, boolean)
JRadioButton()
Creates a JRadioButton instance. The string argument specifies the text, if any, that the radio button should display. Similarly, the Icon argument specifies the image that should be used instead of the look and feel's default radio button image. Specifying the boolean argument as true initializes the radio button to be selected, subject to the approval of the ButtonGroup object. If the boolean argument is absent or false, then the radio button is initially unselected.
And the methods are similar to JCheckBox In below is an example modified form Sun's Java tutorial.

RadioButtonTest.java

You can get the program here.
Download the pictures and save it in the same folder.
bird
cat
dog
rab
pig
Here is the output of the program
a
b
   1:import java.awt.*;
   2:import javax.swing.*;
   3:import java.awt.event.*;
   4:
   5:public class RadioButtonTest extends JFrame {
   6:    // name of the animals
   7:    static String birdString = "Bird";
   8:    static String catString = "Cat";
   9:    static String dogString = "Dog";
  10:    static String rabbitString = "Rabbit";
  11:    static String pigString = "Pig";
  12:    // picture to display the animal pictures
  13:    JLabel picture = new JLabel();
  14:    
  15:    public RadioButtonTest() {
  16:        // instantiate radio buttons
  17:        JRadioButton birdButton = new JRadioButton(birdString);
  18:        JRadioButton catButton = new JRadioButton(catString);
  19:        JRadioButton dogButton = new JRadioButton(dogString);
  20:        JRadioButton rabbitButton = new JRadioButton(rabbitString);
  21:        JRadioButton pigButton = new JRadioButton(pigString);
  22:        
  23:        //add the buttons to a group
  24:        ButtonGroup group = new ButtonGroup();
  25:        group.add(birdButton);
  26:        group.add(catButton);
  27:        group.add(dogButton);
  28:        group.add(rabbitButton);
  29:        group.add(pigButton);
  30:        
  31:        // select the bird as the first picture
  32:        birdButton.setSelected(true);
  33:        picture.setIcon(new ImageIcon(birdString + ".gif"));
  34:        
  35:        // add radio buttons to a panel
  36:        JPanel animalPanel = new JPanel(new GridLayout(0,1));
  37:        animalPanel.add(birdButton);
  38:        animalPanel.add(catButton);
  39:        animalPanel.add(dogButton);
  40:        animalPanel.add(rabbitButton);
  41:        animalPanel.add(pigButton);
  42:
  43:        // add animalPanel and picture to the JFrame
  44:        getContentPane().add(animalPanel, BorderLayout.WEST); 
  45:        getContentPane().add(picture); // add to the center
  46:        
  47:        // Register a listener for the radio buttons.
  48:        AnimalListener myListener = new AnimalListener();
  49:        birdButton.addActionListener(myListener);
  50:        catButton.addActionListener(myListener);
  51:        dogButton.addActionListener(myListener);
  52:        rabbitButton.addActionListener(myListener);
  53:        pigButton.addActionListener(myListener);
  54:    }
  55:    
  56:    // inner class
  57:    // we define a class inside another class
  58:    // the class has access to all the members 
  59:    class AnimalListener implements ActionListener { 
  60:        public void actionPerformed(ActionEvent e) {
  61:            // set the picture
  62:            // the inner class can access the private member : picture
  63:            picture.setIcon(new ImageIcon(e.getActionCommand()+".gif"));
  64:        }
  65:    }
  66:    
  67:    public static void main(String[] args) {
  68:        RadioButtonTest f = new RadioButtonTest();
  69:        f.setTitle("Animals");
  70:        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  71:        f.pack();
  72:        f.setVisible(true);
  73:    }
  74:}

Explanation

line 17 - 21 create RadioButton.
line 32 - 41 put the buttons to a panel. Add the panel to the frame.
line 43 - 58 add ActionListener

ButtonGroup

  • We add all the related radio buttons to the a group (line 24-29)
  • only one radio button can be selected form the group.
  • Commonly Used ButtonGroup Constructors/Methods
    Constructor or Method Purpose
    ButtonGroup() Creates a ButtonGroup instance.
    void add(button)
    void remove(button)
    Adds a button to the group, or removes a button from the group.

    Inner class

    Line 59 - 64 :