Checkboxes
Home ] Up ] [ Checkboxes ] Radio Buttons ]

 

 

To give your users the choice of a limited set of options, it's often a good idea to present them with a set of checkboxes.

A checkbox provides an on or off, true or false, or Boolean type of choice.

Because it is a simple, on/off, kind of item, it is considered pretty much like a regular button, and supports ActionEvents in the same way as regular buttons.

For example:

package swingExamples;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

class CheckboxesPanel extends JPanel
{
  public CheckboxesPanel()
  {
    setLayout(new BorderLayout());
    add(new TextPanel(), BorderLayout.CENTER);
    add(new InputPanel(), BorderLayout.SOUTH);
  }
  
  void setTextFont(int style)
  {
    m_text.setFont(new Font("SansSerif", style, 12));
  }
  
  /////// Private data /////
  private JLabel m_text = 
      new JLabel(
      "The quick brown fox jumps over the lazy dog");
  
  /////// Inner classes /////
  class TextPanel extends JPanel
  {
    public TextPanel()
    {
      setBackground(Color.white);
      setTextFont(Font.PLAIN);
      add(m_text);
    }
  }
  
  class InputPanel extends JPanel 
      implements ActionListener
  {
    public InputPanel()
    {
      add(m_boldCheckBox);
      m_boldCheckBox.addActionListener(this);
      add(m_italicCheckBox);
      m_italicCheckBox.addActionListener(this);
    }
    
    public void actionPerformed(ActionEvent ev)
    {
      int style = Font.PLAIN;
      if (m_boldCheckBox.isSelected())
      {
        style |= Font.BOLD;
      }
      if (m_italicCheckBox.isSelected())
      {
        style |= Font.ITALIC;
      }
      setTextFont(style);
    }
    
    ///// Private data /////
    private JCheckBox m_boldCheckBox = 
                        new JCheckBox("Bold");
    private JCheckBox m_italicCheckBox = 
                        new JCheckBox("Italic");
  }
}

class CheckboxesFrame extends JFrame
{
  public CheckboxesFrame()
  {
    setTitle("CheckBoxes");
    setSize(300, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container contentPane = getContentPane();
    contentPane.add( new CheckboxesPanel() );
  }
}

public class Checkboxes
{
  public static void main(String[] args)
  {
    CheckboxesFrame frame = new CheckboxesFrame();
    frame.setVisible(true);
  }
}

which displays:

 

This page was last modified on 02 October, 2007