你好,我一直在堅持如何使一個按鈕顯示一個隨機number.this是我現在的位置。我無法弄清楚隨機數發生器代碼的去向。如果我將它放在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);
}
});
}
}
的[無法指非最終變量在不同的方法定義的內部類中]可能的複製(http://stackoverflow.com/questions/1299837/cannot-refer一個非最終變量在內部類中定義的差異) –