import javax.swing.*;
public class First{
public static void main(String args[]){
// Making an object for the Second class
Second gui = new Second();
// Setting the default close operation to exit
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Setting the size
gui.setSize(400, 300);
// Setting the visibility
gui.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
// Inheriting JFrame ** REQUIRED **
public class Second extends JFrame {
private JTextField txtF;
private Font plainF, boldF, italicF, boldItalicF;
private JRadioButton plainB, boldB, italicB, boldItalicB;
private ButtonGroup group;
public Second(){
super("Title");
setLayout(new FlowLayout());
txtF = new JTextField("Text Field", 25);
add(txtF);
plainB = new JRadioButton("Plain Button", true);
boldB = new JRadioButton("Bold Button", false);
italicB = new JRadioButton("Italic Button", false);
boldItalicB = new JRadioButton("Bold Italic Button", false);
add(plainB);
add(boldB);
add(italicB);
add(boldItalicB);
// Assigning the group variable
group = new ButtonGroup();
// Adding the buttons to the group which will let the program know which buttons to uncheck when another button is clicked.
group.add(plainB);
group.add(boldB);
group.add(italicB);
group.add(boldItalicB);
plainF = new Font("Tahoma", Font.PLAIN, 14);
boldF = new Font("Tahoma", Font.BOLD, 14);
italicF = new Font("Tahoma", Font.ITALIC, 14);
boldItalicF = new Font("Tahoma", Font.BOLD + Font.ITALIC, 14);
txtF.setFont(plainF);
// Waits for event to happen, pass in font object to constructor
plainB.addItemListener(new HandlerClass(plainF));
boldB.addItemListener(new HandlerClass(boldF));
italicB.addItemListener(new HandlerClass(italicF));
boldItalicB.addItemListener(new HandlerClass(boldItalicF));
}
private class HandlerClass implements ItemListener{
private Font font;
// Font object gets variable font
public HandlerClass(Font f){
font = f;
}
// Sets the font to the font object that has been passed
public void itemStateChanged(ItemEvent click){
txtF.setFont(font);
}
}
}