Java JRadioButton handle selection change event

Description

Java JRadioButton handle selection change event

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

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class Main extends JFrame {
  private JTextField textField = new JTextField("this is a test from demo2s.com", 25);
  private Font plainFont;
  private Font boldFont;
  private Font italicFont;
  private Font boldItalicFont;
  private JRadioButton plainJRadioButton = new JRadioButton("Plain", true);
  private JRadioButton boldJRadioButton = new JRadioButton("Bold", false);
  private JRadioButton italicJRadioButton = new JRadioButton("Italic", false);
  private JRadioButton boldItalicJRadioButton = new JRadioButton("Bold/Italic", false);
  private ButtonGroup  radioGroup = new ButtonGroup();  // buttongroup to hold radio buttons

  public Main() {
    super("RadioButton Test");
    setLayout(new FlowLayout());
   /*ww  w.  jav  a  2  s. c o  m*/
    add(textField); 
    add(plainJRadioButton); 
    add(boldJRadioButton); 
    add(italicJRadioButton); 
    add(boldItalicJRadioButton); 

    // create logical relationship between JRadioButtons
   
    radioGroup.add(plainJRadioButton); // add plain to group
    radioGroup.add(boldJRadioButton); // add bold to group
    radioGroup.add(italicJRadioButton); // add italic to group
    radioGroup.add(boldItalicJRadioButton); // add bold and italic

    // create font objects
    plainFont = new Font("Serif", Font.PLAIN, 14);
    boldFont = new Font("Serif", Font.BOLD, 14);
    italicFont = new Font("Serif", Font.ITALIC, 14);
    boldItalicFont = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
    textField.setFont(plainFont);

    // register events for JRadioButtons
    plainJRadioButton.addItemListener(new RadioButtonHandler(plainFont));
    boldJRadioButton.addItemListener(new RadioButtonHandler(boldFont));
    italicJRadioButton.addItemListener(new RadioButtonHandler(italicFont));
    boldItalicJRadioButton.addItemListener(new RadioButtonHandler(boldItalicFont));
  }

  // private inner class to handle radio button events
  private class RadioButtonHandler implements ItemListener {
    private Font font; // font associated with this listener

    public RadioButtonHandler(Font f) {
      font = f;
    }

    // handle radio button events
    @Override
    public void itemStateChanged(ItemEvent event) {
      textField.setFont(font);
    }
  }

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



PreviousNext

Related