import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.lang.reflect.InvocationTargetException;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class RadioButtonFrame extends JFrame {
private static final long serialVersionUID = -4257293733892482733L;
private JTextField textField = null;
private Font plainFont = null;
private Font italicFont = null;
private Font boldFont = null;
private Font italic_bold_Font = null;
private JRadioButton plainRadioButton ;
private JRadioButton italicRadioButton;
private JRadioButton boldRadioButton;
private JRadioButton italicboldRadioButton;
private ButtonGroup radioGroup ;
public RadioButtonFrame()
{
super("Testing RadioButton");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
setLayout(new FlowLayout());
textField = new JTextField("Watch the font style change",25);
add(textField);
plainRadioButton = new JRadioButton("Plain",true);
italicRadioButton = new JRadioButton("Italic",false);
boldRadioButton = new JRadioButton("Bold",false);
italicboldRadioButton = new JRadioButton("Bold/Italic",false);
add(plainRadioButton);
add(italicRadioButton);
add(boldRadioButton);
add(italicboldRadioButton);
//Create Logical relationship between JRadioButton.
radioGroup = new ButtonGroup();
radioGroup.add(plainRadioButton);
radioGroup.add(italicRadioButton);
radioGroup.add(boldRadioButton);
radioGroup.add(italicboldRadioButton);
//Create font objects.
plainFont = new Font("Serif", Font.PLAIN, 14);
italicFont = new Font("Serif", Font.ITALIC, 14);
boldFont = new Font("Serif", Font.BOLD, 14);
italic_bold_Font = new Font("Serif", Font.BOLD + Font.ITALIC , 14);
textField.setFont(plainFont);
//Register events for JRadioButton.
plainRadioButton.addItemListener(new RadioButtonHandler(plainFont));
italicboldRadioButton.addItemListener(new RadioButtonHandler(italicFont));
boldRadioButton.addItemListener(new RadioButtonHandler(boldFont));
italicboldRadioButton.addItemListener(new RadioButtonHandler(italic_bold_Font));
setVisible(true);
}
private class RadioButtonHandler implements ItemListener{
private Font font = null ;
public RadioButtonHandler(Font f){
font = f ;
}
@Override
public void itemStateChanged(ItemEvent e) {
textField.setFont(font);
}
}
public static void main(String[] args) throws InterruptedException, InvocationTargetException {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
new RadioButtonFrame();
}
});
}
}