0

我正在通过创建一个包含三个单选按钮、一个文本框和一个“开始”按钮的对话框来自学 Java 的 Swing 组件。我已经到了添加单选按钮的地步,并且我的代码遇到了错误。我有一个类调用构造函数来显示对话框。文本字段和“开始”按钮还没有功能;他们只是占位符。

当我运行下面发布的代码时,会按预期显示一个对话框,但我可以同时选择所有三个单选按钮。阅读Oracle 的JButton和“如何使用单选按钮”文档和教程,看来我需要将 a 应用ButtonGroup到 my JRadioButtons,它会自动将它们分组为一个单选关系。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//
public class CreateButtonSel {
    public static void main(String[] args) {
        ButtonSel thisButtonSel = new ButtonSel();
        final int WIDTH = 250;
        final int HEIGHT = 250;
        thisButtonSel.setSize(WIDTH,HEIGHT);
        thisButtonSel.setVisible(true);
    }
}

然而,当我在ButtonSel课堂上取消注释时,尽管似乎遵循教程中提到的语法,在我的语句的打开和关闭括号下使用克拉ButtonGroup返回。来自搜索堆栈的这个错误似乎与不正确地声明变量有关,或者在类中的错误位置。我无法发现那个错误。应该让我访问所有 Button 构造函数,对吗?还有一个我应该加入吗?error: <identifier> expected...Button.add(...)import javax.swing.*

我在这里想念什么?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//
public class ButtonSel extends JFrame {
    JLabel buttonSelLabel = new JLabel("Select One");
    JRadioButton oneButton = new JRadioButton("One", true);
    JRadioButton twoButton = new JRadioButton("Two", false);
    JRadioButton threeButton = new JRadioButton("Three", false);
/*    comment out the following; it runs fine.
 *    uncomment, and I get the following error: 
 *
 *    error: <identifier> expected with carats under the open and close 
 *    parens of my ...Button.add(...) statements. 
 *
    ButtonGroup groupOfRadioButtons = new ButtonGroup();
    groupOfRadioButtons.add(oneButton);
    groupOfRadioButtons.add(twoButton);
    groupOfRadioButtons.add(threeButton);   
*/
    JButton approveButton = new JButton("Go");
    JTextField textDisplay = new JTextField(18);
     //
    JPanel timerPanel = new JPanel();
    JPanel radioPanel = new JPanel(new GridLayout(0, 1));
     //
    public ButtonSel() {
        super("ButtonTest");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        add(buttonSelLabel);
        add(oneButton);
        add(twoButton);
        add(threeButton);
        add(textDisplay);
        add(approveButton);
    }
}
4

1 回答 1

2

您正在尝试在此处执行语句,但它们不在方法或构造函数中:

ButtonGroup groupOfRadioButtons = new ButtonGroup();
groupOfRadioButtons.add(oneButton);
groupOfRadioButtons.add(twoButton);
groupOfRadioButtons.add(threeButton); 

一个类只直接包含方法、构造函数和嵌套类型声明,以及初始化块。

您应该将声明后的三个语句放入构造函数中 - 您可以使用初始化程序块,但在可读性方面通常不是很好。

public class ButtonSel extends JFrame {
    ... other fields ...

    // Note: it's a good idea to make all fields private
    private ButtonGroup groupOfRadioButtons = new ButtonGroup();

    public ButtonSel() {
        super("ButtonTest");
        ...
        groupOfRadioButtons.add(oneButton);
        groupOfRadioButtons.add(twoButton);
        groupOfRadioButtons.add(threeButton);
    }
}
于 2013-04-18T16:35:18.653 回答