2016-03-29 36 views
1

我有一個主要的gui類,它是在NetBeans gui構建器中製作的。我正在創建一個JLabel計時器停機的迷你遊戲。 JLabel位於主要的gui中,定時器位於一個單獨的類中,例如timer。當定時器循環正在循環時,我想讓位於主gui中的JLabel改變(Timer = 10,Timer = 9,...等)。更改java中不同類的標籤文本

查看下面的示例代碼以獲得更好的理解。

這是計時器所在的類:

public class ShapeGame { 

Timer timer; 
int counter = 10; 

ShapeGame() { 

    ActionListener a = new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 

      System.out.println("Counter = " + counter); 
      labTimer.setText("Timer: " + counter); 
      if (--counter < 0) { 
       timer.stop(); 
       System.exit(0); 
      } 
     } 
    }; 

    timer = new Timer(1000, a); 
    timer.start(); 
    } 
} 

這是經修訂的守則將JLabel所在的位置:

(注意:不是所有的代碼已經被添加了一個JLabel和JFrame的只是讀書的目的)

public class mainGui extends JFrame { 

labTimer = new javax.swing.JLabel(); 

    private void gameStartStopActionPerformed(java.awt.event.ActionEvent evt) {            
     ShapeGame sg = new ShapeGame(); 
    } 
} 

我明白這不是從一個不同的類labTimer.setText("Timer: " + counter);調用標籤的正確方法。希望我已經提供了足夠的信息來幫助解決這個問題。

+1

要麼將​​標籤的引用傳遞給ActionListner(不是最佳解決方案),要麼使用ActionLisyener設置觀察者模式,以便它可以在其更改時通知相關方 – MadProgrammer

回答

2

一個可能的簡單(但不是乾淨的)解決方案是將JLabel傳遞到ShapeGame類中,以便它可以直接改變它的狀態。

例如,

public class ShapeGame { 
    Timer timer; 
    int counter = 10; 

    // note change to constructor parameter 
    public ShapeGame(final JLabel label) { 
     ActionListener a = new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       System.out.println("Counter = " + counter); 

       // note changes 
       // labTimer.setText("Timer: " + counter); 
       label.setText("Timer: " + counter); 

       if (--counter < 0) { 
        timer.stop(); 
        System.exit(0); 
       } 
      } 
     }; 

     timer = new Timer(1000, a); 
     timer.start(); 
    } 
} 

然後創建ShapeGame類時,傳遞的JLabel到其構造函數調用。清潔工將構建您的程序la MVC。