当我选择右键并单击 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
});
我是一名优秀的程序员,十分优秀!