49、GUI 应用中的单选按钮、复选框与边框

GUI 应用中的单选按钮、复选框与边框

1. 单选按钮与复选框概述

在 GUI 应用中,单选按钮(Radio Buttons)和复选框(Check Boxes)是常用的用户交互组件。单选按钮通常以两个或更多为一组出现,允许用户从多个可能的选项中选择一个;而复选框可以单独出现或成组出现,允许用户进行“是/否”或“开/关”的选择。

1.1 单选按钮

单选按钮在需要用户从多个选项中选择一个时非常有用。每个单选按钮有一个小圆圈,选中时圆圈会被填充,未选中时则为空。可以使用 JRadioButton 类来创建单选按钮,其构造函数有以下两种常见形式:
- JRadioButton(String text) :创建一个未选中的单选按钮, text 参数指定显示在按钮旁边的文本。
- JRadioButton(String text, boolean selected) :创建一个单选按钮, text 参数指定显示文本, selected 参数为 true 时按钮初始为选中状态,为 false 时初始为未选中状态。

以下是创建单选按钮的示例代码:

JRadioButton radio1 = new JRadioButton("Choice 1"); // 初始未选中
JRadioButton radio2 = new JRadioButton("Choice 2", true); // 初始选中

单选按钮通常需要分组,使用 ButtonGroup 类可以实现这一功能。分组后,同一组中任何时候只能有一个单选按钮被选中,点击一个单选按钮会自动取消同一组中其他按钮的选中状态。以下是分组的示例代码:

// 创建三个单选按钮
JRadioButton radio1 = new JRadioButton("Choice 1", true);
JRadioButton radio2 = new JRadioButton("Choice 2");
JRadioButton radio3 = new JRadioButton("Choice 3");

// 创建 ButtonGroup 对象
ButtonGroup group = new ButtonGroup();

// 将单选按钮添加到 ButtonGroup 对象
group.add(radio1);
group.add(radio2);
group.add(radio3);

当用户点击单选按钮时,会生成一个动作事件(Action Event)。要响应这个事件,需要编写一个动作监听器类,并将该类的实例注册到单选按钮上。以下是一个完整的示例代码,展示了如何创建一个带有单选按钮的窗口,用于将公里转换为英里、英尺或英寸:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

/**
 * The MetricConverter class lets the user enter a
 * distance in kilometers. Radio buttons can be selected to
 * convert the kilometers to miles, feet, or inches.
 */
public class MetricConverter extends JFrame {
    private JPanel panel;                     // A holding panel
    private JLabel messageLabel;              // A message to the user
    private JTextField kiloTextField;         // To hold user input
    private JRadioButton milesButton;         // To convert to miles
    private JRadioButton feetButton;          // To convert to feet
    private JRadioButton inchesButton;        // To convert to inches
    private ButtonGroup radioButtonGroup;     // To group radio buttons
    private final int WINDOW_WIDTH = 400;     // Window width
    private final int WINDOW_HEIGHT = 100;    // Window height

    /**
     * Constructor
     */
    public MetricConverter() {
        // Set the title.
        setTitle("Metric Converter");

        // Set the size of the window.
        setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

        // Specify an action for the close button.
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Build the panel and add it to the frame.
        buildPanel();

        // Add the panel to the frame's content pane.
        add(panel);

        // Display the window.
        setVisible(true);
    }

    /**
     * The buildPanel method adds a label, text field, and
     * and three buttons to a panel.
     */
    private void buildPanel() {
        // Create the label, text field, and radio buttons.
        messageLabel = new JLabel("Enter a distance in kilometers");
        kiloTextField = new JTextField(10);
        milesButton = new JRadioButton("Convert to miles");
        feetButton = new JRadioButton("Convert to feet");
        inchesButton = new JRadioButton("Convert to inches");

        // Group the radio buttons.
        radioButtonGroup = new ButtonGroup();
        radioButtonGroup.add(milesButton);
        radioButtonGroup.add(feetButton);
        radioButtonGroup.add(inchesButton);

        // Add action listeners to the radio buttons.
        milesButton.addActionListener(new RadioButtonListener());
        feetButton.addActionListener(new RadioButtonListener());
        inchesButton.addActionListener(new RadioButtonListener());

        // Create a panel and add the components to it.
        panel = new JPanel();
        panel.add(messageLabel);
        panel.add(kiloTextField);
        panel.add(milesButton);
        panel.add(feetButton);
        panel.add(inchesButton);
    }

    /**
     * Private inner class that handles the event when
     * the user clicks one of the radio buttons.
     */
    private class RadioButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String input;           // To hold the user's input
            String convertTo = "";  // The units we're converting to
            double result = 0.0;    // To hold the conversion

            // Get the kilometers entered.
            input = kiloTextField.getText();

            // Determine which radio button was clicked.
            if (e.getSource() == milesButton) {
                // Convert to miles.
                convertTo = " miles.";
                result = Double.parseDouble(input) * 0.6214;
            } else if (e.getSource() == feetButton) {
                // Convert to feet.
                convertTo = " feet.";
                result = Double.parseDouble(input) * 3281.0;
            } else if (e.getSource() == inchesButton) {
                // Convert to inches.
                convertTo = " inches.";
                result = Double.parseDouble(input) * 39370.0;
            }

            // Display the conversion.
            JOptionPane.showMessageDialog(null, input +
                    " kilometers is " + result + convertTo);
        }
    }

    public static void main(String[] args) {
        new MetricConverter();
    }
}

在代码中,可以使用 isSelected 方法来判断单选按钮是否被选中,使用 doClick 方法在代码中选中单选按钮:

if (radio.isSelected()) {
    // 单选按钮被选中时执行的代码
}

radio.doClick(); // 选中单选按钮

1.2 复选框

复选框外观为一个小方框,旁边带有标签。复选框可以单独或成组显示,与单选按钮不同,复选框通常不需要使用 ButtonGroup 进行分组,因为它们不用于进行互斥选择,用户可以选择组中的任意一个或所有复选框。

可以使用 JCheckBox 类来创建复选框,其构造函数与 JRadioButton 类似:
- JCheckBox(String text) :创建一个未选中的复选框, text 参数指定显示在框旁边的文本。
- JCheckBox(String text, boolean selected) :创建一个复选框, text 参数指定显示文本, selected 参数为 true 时框初始为选中状态,为 false 时初始为未选中状态。

以下是创建复选框的示例代码:

JCheckBox check1 = new JCheckBox("Macaroni"); // 初始未选中
JCheckBox check2 = new JCheckBox("Spaghetti", true); // 初始选中

当复选框被选中或取消选中时,会生成一个项事件(Item Event)。要处理这个事件,需要编写一个项监听器类,该类必须实现 ItemListener 接口,并包含一个 itemStateChanged 方法。以下是一个使用复选框的示例代码,展示了如何根据复选框的状态改变窗口的背景和前景颜色:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * The ColorCheckBoxWindow class demonstrates how check boxes
 * can be used.
 */
public class ColorCheckBoxWindow extends JFrame {
    private JLabel messageLabel;        // A message to the user
    private JCheckBox yellowCheckBox;   // To select yellow background
    private JCheckBox redCheckBox;      // To select red foreground
    private final int WINDOW_WIDTH = 300;     // Window width
    private final int WINDOW_HEIGHT = 100;    // Window height

    /**
     * Constructor
     */
    public ColorCheckBoxWindow() {
        // Set the text for the title bar.
        setTitle("Color Check Boxes");

        // Set the size of the window.
        setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

        // Specify an action for the close button.
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Create a label.
        messageLabel = new JLabel("Select the check " +
                "boxes to change colors.");

        // Create the check boxes.
        yellowCheckBox = new JCheckBox("Yellow background");
        redCheckBox = new JCheckBox("Red foreground");

        // Add an item listener to the check boxes.
        yellowCheckBox.addItemListener(new CheckBoxListener());
        redCheckBox.addItemListener(new CheckBoxListener());

        // Add a FlowLayout manager to the content pane.
        setLayout(new FlowLayout());

        // Add the label and check boxes to the content pane.
        add(messageLabel);
        add(yellowCheckBox);
        add(redCheckBox);

        // Display the window.
        setVisible(true);
    }

    /**
     * Private inner class that handles the event when
     * the user clicks one of the check boxes.
     */
    private class CheckBoxListener implements ItemListener {
        public void itemStateChanged(ItemEvent e) {
            // Determine which check box was clicked.
            if (e.getSource() == yellowCheckBox) {
                // Is the yellow check box selected? If so, we
                // want to set the background color to yellow.
                if (yellowCheckBox.isSelected()) {
                    // The yellow check box was selected. Set
                    // the background color for the content
                    // pane and the two check boxes to yellow.
                    getContentPane().setBackground(Color.YELLOW);
                    yellowCheckBox.setBackground(Color.YELLOW);
                    redCheckBox.setBackground(Color.YELLOW);
                } else {
                    // The yellow check box was deselected. Set
                    // the background color for the content
                    // pane and the two check boxes to light gray.
                    getContentPane().setBackground(Color.LIGHT_GRAY);
                    yellowCheckBox.setBackground(Color.LIGHT_GRAY);
                    redCheckBox.setBackground(Color.LIGHT_GRAY);
                }
            } else if (e.getSource() == redCheckBox) {
                // Is the red check box selected? If so, we want
                // to set the foreground color to red.
                if (redCheckBox.isSelected()) {
                    // The red check box was selected. Set the
                    // foreground color for the label and the
                    // two check boxes to red.
                    messageLabel.setForeground(Color.RED);
                    yellowCheckBox.setForeground(Color.RED);
                    redCheckBox.setForeground(Color.RED);
                } else {
                    // The red check box was deselected. Set the
                    // foreground color for the label and the
                    // two check boxes to black.
                    messageLabel.setForeground(Color.BLACK);
                    yellowCheckBox.setForeground(Color.BLACK);
                    redCheckBox.setForeground(Color.BLACK);
                }
            }
        }
    }

    public static void main(String[] args) {
        new ColorCheckBoxWindow();
    }
}

同样,可以使用 isSelected 方法来判断复选框是否被选中,使用 doClick 方法在代码中选中复选框:

if (checkBox.isSelected()) {
    // 复选框被选中时执行的代码
}

checkBox.doClick(); // 选中复选框

1.3 单选按钮与复选框的对比

组件类型 选择方式 分组需求 事件类型
单选按钮 从多个选项中选一个 需要使用 ButtonGroup 分组 动作事件(Action Event)
复选框 可选择任意个选项 通常不需要分组 项事件(Item Event)

1.4 操作流程总结

以下是使用单选按钮和复选框的操作流程:
1. 创建组件 :使用 JRadioButton JCheckBox 类的构造函数创建单选按钮或复选框。
2. 分组(单选按钮) :使用 ButtonGroup 类对单选按钮进行分组。
3. 添加到容器 :将组件添加到 JPanel 或其他容器中。
4. 注册监听器 :为组件注册相应的监听器(动作监听器或项监听器)。
5. 处理事件 :在监听器的方法中编写处理事件的代码。

1.5 流程图

graph TD;
    A[创建组件] --> B[分组(单选按钮)];
    B --> C[添加到容器];
    C --> D[注册监听器];
    D --> E[处理事件];

通过以上介绍,我们了解了单选按钮和复选框的基本使用方法,包括创建、分组、事件处理等。在实际的 GUI 应用开发中,可以根据具体需求选择合适的组件来实现用户交互功能。

2. 边框的使用

在 GUI 应用中,为组件或一组组件添加边框可以使界面更加清晰和有条理。边框能够将相关的组件组合在一起,让窗口看起来更具组织性。

2.1 边框概述

可以使用 Border 对象来指定边框的细节,而创建 Border 对象的首选方式是使用 BorderFactory 类。 JPanel 组件有一个 setBorder 方法,用于为面板添加边框,该方法接受一个 Border 对象作为参数。

BorderFactory 类有多种方法可以创建不同类型的边框,常见的边框类型及其对应的创建方法如下表所示:
| 边框类型 | BorderFactory 方法 | 描述 |
| ---- | ---- | ---- |
| 复合边框(Compound border) | createCompoundBorder | 有两部分的边框:内边缘和外边缘,内外边缘可以是其他类型的边框。 |
| 空边框(Empty border) | createEmptyBorder | 组件边缘周围的空白空间。 |
| 蚀刻边框(Etched border) | createEtchedBorder | 具有 3D 外观,看起来像是“蚀刻”在背景中。 |
| 线边框(Line border) | createLineBorder | 围绕组件边缘的线条。 |
| 凹陷斜面边框(Lowered bevel border) | createLoweredBevelBorder | 看起来像斜面边缘,具有 3D 外观,给人一种沉入周围背景的错觉。 |
| 磨砂边框(Matte border) | createMatteBorder | 可以有不同厚度边缘的线边框。 |
| 凸起斜面边框(Raised bevel border) | createRaisedBevelBorder | 看起来像斜面边缘,具有 3D 外观,给人一种高于周围背景的错觉。 |
| 标题边框(Titled border) | createTitledBorder | 带有标题的蚀刻边框。 |

2.2 空边框

空边框是组件边缘周围的空白空间。要创建空边框,可以调用 BorderFactory 类的 createEmptyBorder 方法,其一般格式如下:

BorderFactory.createEmptyBorder(int top, int left, int bottom, int right);

其中, top left bottom right 参数分别指定边框顶部、左侧、底部和右侧边缘的像素大小。该方法返回一个 Border 对象的引用。

以下是一个使用示例,假设 panel 变量引用一个 JPanel 对象:

panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

执行此语句后, panel 引用的 JPanel 将在每个边缘周围有一个 5 像素的空边框。

2.3 线边框

线边框是围绕组件边缘的指定颜色和厚度的线条。要创建线边框,可以调用 BorderFactory 类的 createLineBorder 方法,其一般格式如下:

BorderFactory.createLineBorder(Color color, int thickness);

color 参数指定线条的颜色, thickness 参数指定线条的像素大小。该方法返回一个 Border 对象的引用。

以下是一个使用示例,假设 panel 变量引用一个 JPanel 对象:

panel.setBorder(BorderFactory.createLineBorder(Color.RED, 1));

执行此语句后, panel 引用的 JPanel 将在其边缘周围有一个 1 像素厚的红色线边框。

2.4 标题边框

标题边框是带有标题的蚀刻边框。要创建标题边框,可以调用 BorderFactory 类的 createTitledBorder 方法,其一般格式如下:

BorderFactory.createTitledBorder(String title);

title 参数是要显示为边框标题的文本。该方法返回一个 Border 对象的引用。

以下是一个使用示例,假设 panel 变量引用一个 JPanel 对象:

panel.setBorder(BorderFactory.createTitledBorder("Choices"));

执行此语句后, panel 引用的 JPanel 将有一个带有标题“Choices”的蚀刻边框。

2.5 操作流程总结

以下是为组件添加边框的操作流程:
1. 导入必要的包 :如果使用 BorderFactory 类,需要添加 import javax.swing.*; 语句。
2. 创建边框对象 :使用 BorderFactory 类的相应方法创建所需类型的边框。
3. 设置边框 :使用 JPanel 等组件的 setBorder 方法将边框应用到组件上。

2.6 流程图

graph TD;
    A[导入必要的包] --> B[创建边框对象];
    B --> C[设置边框];

2.7 综合示例

以下是一个综合使用单选按钮、复选框和边框的示例代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ComprehensiveExample extends JFrame {
    private JPanel panel;
    private JLabel messageLabel;
    private JTextField inputField;
    private JRadioButton option1;
    private JRadioButton option2;
    private JCheckBox checkBox;
    private ButtonGroup radioGroup;

    public ComprehensiveExample() {
        setTitle("Comprehensive Example");
        setSize(400, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        buildPanel();
        add(panel);

        setVisible(true);
    }

    private void buildPanel() {
        panel = new JPanel();
        messageLabel = new JLabel("Enter some text:");
        inputField = new JTextField(10);
        option1 = new JRadioButton("Option 1");
        option2 = new JRadioButton("Option 2");
        checkBox = new JCheckBox("Enable feature");

        radioGroup = new ButtonGroup();
        radioGroup.add(option1);
        radioGroup.add(option2);

        option1.addActionListener(new RadioListener());
        option2.addActionListener(new RadioListener());
        checkBox.addItemListener(new CheckBoxListener());

        // 添加空边框
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        panel.add(messageLabel);
        panel.add(inputField);
        panel.add(option1);
        panel.add(option2);
        panel.add(checkBox);
    }

    private class RadioListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == option1) {
                System.out.println("Option 1 selected");
            } else if (e.getSource() == option2) {
                System.out.println("Option 2 selected");
            }
        }
    }

    private class CheckBoxListener implements ItemListener {
        public void itemStateChanged(ItemEvent e) {
            if (checkBox.isSelected()) {
                System.out.println("Feature enabled");
            } else {
                System.out.println("Feature disabled");
            }
        }
    }

    public static void main(String[] args) {
        new ComprehensiveExample();
    }
}

通过以上内容,我们详细了解了在 GUI 应用中使用单选按钮、复选框和边框的方法。在实际开发中,可以根据界面设计和用户交互的需求,灵活运用这些组件和技术,打造出更加美观、易用的 GUI 应用程序。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值