[英]How to change label text of .fxml file from another java class(means out side the controller)?
[英]Change Label text from different class in java
我有一個主要的gui類,它是在NetBeans gui生成器中制作的。 我正在創建一個迷你游戲,其中JLabel計時器關閉。 JLabel位於主gui中,而計時器位於稱為timer
的單獨類中。 當計時器循環循環時,我希望更改位於主GUI中的JLabel(Timer = 10,Timer = 9,...等)。
查看下面的示例代碼以更好地理解。
這是計時器所在的類:
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);
調用類的正確方法labTimer.setText("Timer: " + counter);
。 希望我提供了足夠的信息來幫助解決此問題。
一種可能的簡單(但不是干凈的)解決方案是將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傳遞到其構造函數調用中。 更干凈的是將您的程序構建為MVC。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.