Java JCheckBox handle click selection change event

Description

Java JCheckBox handle click selection change event


import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main extends JFrame {
  private final JTextField textField; // displays text in changing fonts
  private final JCheckBox boldJCheckBox; 
  private final JCheckBox italicJCheckBox; 

  public Main() {
    super("JCheckBox Test");
    setLayout(new FlowLayout());

    // set up JTextField and set its font
    textField = new JTextField("Watch the font style change", 20);
    textField.setFont(new Font("Serif", Font.PLAIN, 14));
    add(textField); // add textField to JFrame

    boldJCheckBox = new JCheckBox("Bold");
    italicJCheckBox = new JCheckBox("Italic");
    add(boldJCheckBox);//from  ww  w  . ja va2  s .  c o  m
    add(italicJCheckBox);

    // register listeners for JCheckBoxes
    CheckBoxHandler handler = new CheckBoxHandler();
    boldJCheckBox.addItemListener(handler);
    italicJCheckBox.addItemListener(handler);
  }

  // private inner class for ItemListener event handling
  private class CheckBoxHandler implements ItemListener {

    @Override
    public void itemStateChanged(ItemEvent event) {
      Font font = null; // stores the new Font

      // determine which CheckBoxes are checked and create Font
      if (boldJCheckBox.isSelected() && italicJCheckBox.isSelected())
        font = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
      else if (boldJCheckBox.isSelected())
        font = new Font("Serif", Font.BOLD, 14);
      else if (italicJCheckBox.isSelected())
        font = new Font("Serif", Font.ITALIC, 14);
      else
        font = new Font("Serif", Font.PLAIN, 14);

      textField.setFont(font);
    }
  }

  public static void main(String[] args) {
    Main Main = new Main();
    Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Main.setSize(275, 100);
    Main.setVisible(true);
  }
}



PreviousNext

Related