gpt4 book ai didi

java - 从 JRadioButton 获取值

转载 作者:太空宇宙 更新时间:2023-11-04 11:31:37 26 4
gpt4 key购买 nike

当我选择右键并单击 JRadio 框架上的“确定”时,我想更改变量“名称”的值。

例如,当我选择 r1 并点击“确定”时,我希望整个包中包含 name==“Fast”。

package Snake;
public class Radio extends JFrame {
private int delay = 100;
private String name;
JTextField t1;
JButton b;
JRadioButton r1, r2;
JLabel l;

public void selectSpeed() {

b = new JButton("Ok");
r1 = new JRadioButton("Fast");
r2 = new JRadioButton("Slow");
l = new JLabel("Speed: ");

ButtonGroup bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
add(b);
add(r1);
add(r2);
add(l);

b.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) {

if (r1.isSelected()) {
name = "Fast";
} else {
name = "Slow";
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
} // name=="Slow" when r2 is selected
});
if (name == "Fast") { // and now name is empty...
delay = 50;

}
if (name == "Slow") {
delay = 500;
}

setLayout(new FlowLayout());
setSize(400, 400);
setVisible(true);
}

public int setSpeed() {
selectSpeed();
return delay;

}

}

最佳答案

如果您想更改按钮单击上的延迟,您需要在ActionListener本身中编写逻辑,因为您编写的用于更改延迟的代码只会运行一次,而且在程序执行开始时也会运行一次,那时,name将为空。

那么当你点击按钮时,它只会执行ActionListener,所以delay不会随时改变。您犯的另一个错误是您以错误的方式比较字符串。欲了解更多信息,请查看 How do I compare Strings in Java?

要动态更改按钮单击时的延迟,您需要在 ActionListener 中更改它。

 b.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) {

if (r1.isSelected()) {
name = "Fast";
delay = 50;
} else {
name = "Slow";
delay = 500;
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
} // name=="Slow" when r2 is selected
});

关于java - 从 JRadioButton 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43709482/

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