2015-10-07 563 views
1

你好,我一直在堅持如何使一個按鈕顯示一個隨機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); 
      } 
     }); 

    } 

} 
+1

的[無法指非最終變量在不同的方法定義的內部類中]可能的複製(http://stackoverflow.com/questions/1299837/cannot-refer一個非最終變量在內部類中定義的差異) –

回答

2

您可以致電setTextJButton。另外,不要忘記設置默認關閉操作。你不能從外部範圍引用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)); 
    } 
}); 
+0

我仍然收到相同的錯誤消息。我使用了你輸入的內容。 –

+0

@sawg我在Java 8中測試了我的例子。上面是主要的方法,它在這裏工作。 –

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); 
    } 
});