2015-11-02 51 views
2

我想换一个JLabel的文本我创建它的方法之外。的Java改变的JLabel的文本内的另一种方法

我已经通过其他页面看上去就同一主题,但我现在还不能让它工作。也许我自己缺乏Java的知识来解决这个问题。 你能帮我吗?

package autumn; 

import java.awt.EventQueue; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 

public class Main { 

    private JFrame frame; 

    JLabel TestLabel; 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        Main window = new Main(); 
        window.frame.setVisible(true); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 
    public Main() { 
     initialize(); 
     setText(); 
    } 
    private void initialize() { 
     frame = new JFrame(); 
     frame.setBounds(100, 100, 450, 300); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().setLayout(null); 

     JLabel TestLabel = new JLabel(""); 
     TestLabel.setBounds(0, 0, 46, 14); 
     frame.getContentPane().add(TestLabel); 
    } 
    void setText() { 
     TestLabel.setText("Works!"); 
    } 
} 

回答

1

您有一个班级字段JLabel TestLabel

但在initialize方法通过使用一个局部变量具有相同名称的阴影在这领域:

JLabel TestLabel = new JLabel(""); 

因此类字段没有初始化,并setText以后调用失败。

所以干脆写:

TestLabel = new JLabel(""); // assigns to Main.TestLabel 
+0

谢谢!你拯救了我的生命......和我的软件的未来 –

相关问题