Advertisement
makispaiktis

7. Create checkboxes using swing

May 17th, 2022 (edited)
1,086
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.util.logging.Handler;
  4. import javax.swing.*;
  5.  
  6. public class Gui extends JFrame{
  7.  
  8.     // Variables
  9.     private JTextField tf;
  10.     private JCheckBox boldbox;
  11.     private JCheckBox italicbox;
  12.  
  13.     // Constructor
  14.     public Gui(){
  15.  
  16.         // Basics
  17.         super("JFrame's title");
  18.         setLayout(new FlowLayout());
  19.  
  20.         // Create the objects - variables
  21.         tf = new JTextField("This is a sentence", 20);
  22.         tf.setFont(new Font("Serif", Font.PLAIN, 14));
  23.         add(tf);
  24.         boldbox = new JCheckBox("Bold");
  25.         italicbox = new JCheckBox("Italic");
  26.         add(boldbox);
  27.         add(italicbox);
  28.  
  29.         // Handler things in !!!! ItemListener !!!!
  30.         HandlerClass handler = new HandlerClass();
  31.         boldbox.addItemListener(handler);
  32.         italicbox.addItemListener(handler);
  33.     }
  34.  
  35.     private class HandlerClass implements ItemListener{
  36.         public void itemStateChanged(ItemEvent event){
  37.             Font font = null;
  38.             if(boldbox.isSelected() && italicbox.isSelected()){
  39.                 font = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
  40.             }
  41.             else if(boldbox.isSelected()){
  42.                 font = new Font("Serif", Font.BOLD , 14);
  43.             }
  44.             else if(italicbox.isSelected()){
  45.                 font = new Font("Serif", Font.ITALIC , 14);
  46.             }
  47.             else{
  48.                 font = new Font("Serif", Font.PLAIN , 14);
  49.             }
  50.             tf.setFont(font);
  51.         }
  52.     }
  53.  
  54.     // Main
  55.     public static void main(String[] args){
  56.         Gui gui = new Gui();
  57.         gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
  58.         gui.setSize(600, 600);
  59.         gui.setVisible(true);
  60.     }
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement