java 一个JRadioButton

Posted

tags:

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

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

    }

    
}

以上是关于java 一个JRadioButton的主要内容,如果未能解决你的问题,请参考以下文章

在学习枯燥的Java中遇见美丽的Jframe,窗体中的单选按钮(JRadioButton)

java单选按钮传值

单选与复选控件JRadioButton与JCheckBox的使用

为啥我的 JRadioButton 在这种情况下不起作用?

从 ButtonGroup 中获取所有 JRadioButton

检测 JRadioButton 状态更改