我正在通过创建一个带有三个单选按钮,一个文本框和一个“go”按钮的对话框来自学Java的swing组件。我已经到了我正在添加Radio Buttons的地步,并且我的代码遇到了错误。我有一个类调用构造函数来显示对话框。文本字段和“开始”按钮尚无功能;他们只是占位符。
当我运行下面发布的代码时,会按预期显示一个对话框,但我可以同时选择所有三个单选按钮。阅读Oracle's JButton
和“How to use Radio Buttons”文档和教程,似乎我需要将ButtonGroup
应用于我的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
课程中取消注释所提到的代码时,尽管似乎遵循教程中提到的error: <identifier> expected
返回...Button.add(...)
的语法,其中包含carat我的import javax.swing.*
陈述的密切关注。来自搜索堆栈的这个错误似乎与不正确地声明varibale或在类中的错误位置相关联。我无法发现这个错误。 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);
}
}
应该允许我访问所有Button构造函数,对吗?还有其他我应该加入吗?
我在这里缺少什么?
{{1}}
答案 0 :(得分: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);
}
}