您好我一直坚持如何让按钮显示随机数。这就是我现在所处的位置。我无法弄清楚随机数生成器代码的位置。如果我把它放在ActionListener之前,如果它只是在按钮旁边发布而不是在按下按钮时出现。它一直给我错误信息
错误: 无法引用封闭范围内定义的非最终局部变量num1。
请参阅以下代码:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import java.util.Random;
public class myTest {
public static void main(String[] args) {
Random generator = new Random();
int num1;
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
num1 = generator.nextInt(101);
System.out.println("the random number is:" +num1);
JButton button1 = new JButton("Push Me!");
frame.add(panel);
panel.add(button1);
frame.setVisible(true);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
num1 = generator.nextInt(101);
System.out.println("the random number is:" +num1);
}
});
}
}
答案 0 :(得分:2)
您可以在setText
上致电JButton
。另外,不要忘记设置默认的关闭操作。您无法从外部范围引用num1
。我想你想要像
Random generator = new Random();
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
int num1 = generator.nextInt(101);
System.out.println("the random number is:" + num1);
JButton button1 = new JButton(String.format("Push Me! %d", num1));
frame.add(panel);
panel.add(button1);
frame.pack();
frame.setVisible(true);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int num1 = generator.nextInt(101);
System.out.println("the random number is:" + num1);
button1.setText(String.format("Push Me! %d", num1));
}
});
答案 1 :(得分:0)
该错误与num1
被声明为具有main
上下文的局部变量这一事实有关,但在将来的某个时候可能会发生变化。
请查看Referencing non-final variable: why does this code compile?以获取更多解释
相反,因为在ActionListener
被调用之前不需要它,所以只需将其提供给ActionListener
本身
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int num1 = generator.nextInt(101);
System.out.println("the random number is:" + num1);
}
});