import javax.swing.*;
public class First{
public static void main(String args[]){
Second gui = new Second();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(300, 200);
gui.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
// Second class inherits JFrame
public class Second extends JFrame{
// Making TextField variable
private JTextField txtBox;
// Making CheckBox variables
private JCheckBox boldBox, italicBox;
// Creating a constructor
public Second(){
// Setting the title
super("Title");
// Setting the layout
setLayout(new FlowLayout());
// Assigning txtBox variable to a textfield
txtBox = new JTextField("Sentence", 20);
// Assigning txtField font. Font name = Serif, Font format = Plain, Size = 14
txtBox.setFont(new Font("Serif", Font.PLAIN, 14));
// Adding variable
add(txtBox);
// Assigning boldBox and italicBox to CheckBox
boldBox = new JCheckBox("Bold");
italicBox = new JCheckBox("Italic");
// Adding boldbox and italicBox
add(boldBox);
add(italicBox);
// Creating object for the handling class
HandlerClass handler = new HandlerClass();
// Assigning the event to the checkboxes
boldBox.addItemListener(handler);
italicBox.addItemListener(handler);
}
// Creating the handling class
private class HandlerClass implements ItemListener{
public void itemStateChanged(ItemEvent event){
// Making a variable for the font
Font font;
// Checking for checkboxes checked and giving them an action to execute when condition is met
if(boldBox.isSelected() && italicBox.isSelected()){
font = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
} else if (boldBox.isSelected()){
font = new Font("Serif", Font.BOLD, 14);
} else if (italicBox.isSelected()) {
font = new Font("Serif", Font.ITALIC, 14);
} else {
// If none of the checkboxes are checked the font will default
font = null;
}
// Setting the font
txtBox.setFont(font);
}
}
}