2012-11-15 72 views
1

我有以下類繪製標籤。 (我只在這裏給出部分代碼)。 Everyhting正常工作,標籤得到顯示。從另一個類更改JLabel文本

現在,我有另一個類叫Caller類。我有一個方法,我將用它來改變這個標籤的值。我該怎麼做

public class MyClass{ 

    private JLabel label; 

    MyClass(){ 

     run(); 
    } 

    public void editTheLabelsValue (String text) { 
     label.setText(text); 
     frame.repaint(); 
    } 


    run(){ 
      .... // there were more code here, i removed it as it's not relevant to the problem 
     label = new JLabel("Whooo"); 
     label.setBounds(0, 0, 50, 100); 
     frame.getContentPane().add(label); 
      ..... 
    } 

後來,我將使用下面的類來更改上述標籤的文本。我怎樣才能做到這一點。

public class Caller { 

void methodA(){ 
MyClass mc = new MyClass(); 
mc.editTheLabelsValue("Hello"); 
} 

} 

1)當執行了methodA(),文本Hello是沒有得到顯示在標籤字段。它仍然保持爲Whooo。我如何糾正這一點。一旦該方法被執行,我希望標籤文本爲Hello

+1

您的代碼似乎按照指定的方式工作。那它不起作用呢? – PearsonArtPhoto

+0

執行'methodA()'時,文本'Hello'沒有顯示在Label字段上。它仍然是'Whooo' –

+0

你是否在調用'label.setBounds(0,0,50,100);'? – Reimeus

回答

2

我可以看到的直覺問題看起來似乎是使用null佈局,或者您不明白布局管理器的工作方式。

以下代碼通過setText方法調用更新子類中的主類中的標籤。這種方法被稱爲每秒

enter image description here

public class PaintMyLabel { 

    private int counter = 0; 

    public static void main(String[] args) { 
     new PaintMyLabel(); 
    } 

    public PaintMyLabel() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       final MasterPane master = new MasterPane(); 

       JFrame frame = new JFrame(); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(master); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 

       Timer timer = new Timer(1000, new ActionListener() { 

        @Override 
        public void actionPerformed(ActionEvent e) { 
         counter++; 
         master.setText("Now updated " + counter + " times"); 
        } 
       }); 
       timer.setRepeats(true); 
       timer.setCoalesce(true); 
       timer.start(); 

      } 
     }); 
    } 

    public class MasterPane extends JPanel { 

     private JLabel label; 

     public MasterPane() { 
      label = new JLabel("Original text"); 
      setLayout(new GridBagLayout()); 
      add(label); 
     } 

     public void setText(String text) { 
      label.setText(text); 
     } 

    } 

} 

如果您使用的是null佈局,然後停止。不要。只有非常少的幾次你會使用null佈局,我懷疑這不是其中之一。