我正在通过创建一个包含三个单选按钮、一个文本框和一个“开始”按钮的对话框来自学 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);
}
}