[英]Event Handling in JavaFX
我對事件處理的所有話題感到困惑。
我正在嘗試開發一個游戲。 我已經分別編寫了游戲邏輯和GUI(在JavaFX上)。
下面是一些示例代碼; 我該怎么做,以便只要執行setScore(...)
方法, updateScoresLabel()
方法就可以運行?
public class MyGameLogic
{
private int scores=0;
public void setScore(int scores)
{
this.scores=scores;
}
public int getScore()
{
return scores;
}
}
public class JustAGUIExample
{
Label scoresLabel;
MyGameLogic gameLogic;
public void updateScoresLabel()
{
this.scoresLabel=gameLogic.getScore();
}
}
使用綁定而不是事件處理程序
發生模型更改時,不需要事件處理程序即可完成標簽更新。
您可以將 label屬性綁定到模型屬性,然后在更改模型時,標簽將自動更新。
根據您的問題改編代碼以使用綁定。
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.control.Label;
public class MyGameLogic {
private IntegerProperty scores = new SimpleIntegerProperty(0);
public void setScore(int scores) {
this.scores.set(scores);
}
public int getScore() {
return scores.get();
}
public IntegerProperty scoreProperty() {
return scores;
}
}
class JustAGUIExample {
private Label scoresLabel;
private MyGameLogic gameLogic;
public JustAGUIExample() {
scoresLabel.textProperty().bind(
gameLogic.scoreProperty().asString()
);
}
}
在此JavaFX井字游戲示例中,有大量的此類綁定策略示例 。
對於更復雜的邏輯,請使用ChangeListener
假設您還想在樂譜變化時播放勝利聲音,則可以使用以下方法:
class JustAGUIExample {
private Label scoresLabel;
private MyGameLogic gameLogic;
private AudioClip levelUpAudio = new AudioClip("levelup.mp3");
public JustAGUIExample() {
scoresLabel.textProperty().bind(
gameLogic.scoreProperty().asString()
);
gameLogic.scoreProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
levelUpAudio.play();
}
});
}
}
因此, ChangeListener類似於屬性更改的事件偵聽器。 但是我只說這是因為在JavaFX事件中有各自獨立的事物,通常保留給GUI系統事件,例如鼠標單擊,窗口大小調整通知,觸摸板滑動等。
使用Java 8的語法更好:
gameLogic.scoreProperty().addListener((observable, oldValue, newValue) ->
levelUpAudio.play()
);
Java事件處理教程
即使您實際上不需要問題示例中的事件處理,也可以閱讀Oracle JavaFX事件處理教程,以了解真正的事件是什么以及它們如何工作。
我對基於搖擺的建議的想法
在編寫JavaFX程序時,請不要理會與Swing中的事件處理有關的任何建議。 相反,請學習以JavaFX的方式進行操作,否則您將感到困惑。
為了使GUI運行事件,該類必須實現ActionListener。 由此,必須將actionPerformed方法添加到該類中。
這是該示例的實現
//Run, help, and about are all buttons on this frame
public void actionPerformed(ActionEvent e){
if(e.getSource() == run){ //Check if the event was the run button being pressed
//Run the "run" program
}else if(e.getSource() == about){ //Check if the event was the about button being pressed
//Open welcome
}else if(e.getSource() == help){ //Check if the event was the help button being pressed
//Have the help screen appear
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.