gpt4 book ai didi

java - 在最终的 JRadioButton 上使用 .setText

转载 作者:行者123 更新时间:2023-12-01 23:05:34 25 4
gpt4 key购买 nike

当 JRadioButton 设置为 Final 时,如何更改它的标签?

这是构造函数中的一段代码,其中单选按钮被初始化,当按下复选按钮时,所选单选按钮的值将发送到验证用户答案的​​方法:

final JRadioButton ANSWER1 = new JRadioButton("Empty 1");
final JRadioButton ANSWER2 = new JRadioButton("Empty 2");
final JRadioButton ANSWER3 = new JRadioButton("Empty 3");
final JRadioButton ANSWER4 = new JRadioButton("Empty 4");

JButton CHECK = new JButton("Check");
CHECK.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (ANSWER1.isSelected()){
qAnswered(1);
}
if (ANSWER2.isSelected()){
qAnswered(2);
}
if (ANSWER3.isSelected()){
qAnswered(3);
}
if (ANSWER4.isSelected()){
qAnswered(4);
}

}

});

当选择下一个问题按钮时,单选按钮的文本标签需要更改为下一组答案。不幸的是,由于单选按钮设置为最终状态,这会导致应用程序崩溃。

我该如何继续?

最佳答案

变量的 final 关键字意味着该变量只能初始化一次,但这并不意味着该对象中的字段不能更改。即使JRadioButton引用是finalANSWER4.setText()也永远不会抛出任何最终相关错误。

if (ANSWER1.isSelected()){
qAnswered(1);
ANSWER1.setText("New Text 1"); // This will work
}

要更清楚地了解 final 变量,请参阅 JLS 4.12.4 (强调我的)

A variable can be declared final. A final variable may only be assigned to once. Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors.

It is a compile-time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.

A blank final is a final variable whose declaration lacks an initializer.

Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.

关于java - 在最终的 JRadioButton 上使用 .setText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22828493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com