java 带有Checkbox和字体事件的GUI

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 带有Checkbox和字体事件的GUI相关的知识,希望对你有一定的参考价值。

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);
        }
    }
}

以上是关于java 带有Checkbox和字体事件的GUI的主要内容,如果未能解决你的问题,请参考以下文章

java图形界面 运行时如何在点击鼠标时 改变字体颜色或者大小

将 CheckBox 添加到列表行会丢失我的 onItemClick 事件?

JAVA GUI 事件监听事件 详解 和 案例.

java 事件处理器

java带有checkbox的树型菜单

十. 图形界面(GUI)设计3.标签按钮和按钮事件