public Card(Suit suit, Rank rankString, boolean hide) {
this.suit = suit;
this.rankString = rankString;
this.hide = hide;
if (!this.hide) {
HashMap<String, String> map = cardNames();
String thisCard = suit.toString()+rankString.toString();
Image cardDP = new Image("file:E:/Javaworkspace/Project/resource/"+ map.get(thisCard) +".png");
ImageView iv = new ImageView();
iv.setImage(cardDP);
getChildren().add(new StackPane(iv));
} else {
Image img = new Image("file:E:/Javaworkspace/Project/resource/blank.png");
ImageView iv = new ImageView();
iv.setImage(img);
getChildren().add(new StackPane(iv));
}
}
使用hide = false
生成了一副纸牌。
问题是:当我对特定的 Card
实例使用 setHide()
时,GUI 没有反射(reflect) hide
状态的变化。
这让我相信要么构造函数没有做它应该做的事情,要么 GUI 需要其他东西来理解它需要在卡片正面朝下时显示替代图片。无论哪种情况,我必须做什么才能使更改反射(reflect)在 GUI 中?
最佳答案
每次都需要更新状态,因为构造函数仅被调用一次。在 JavaFX 中实现这一点的最酷方法是使用属性绑定(bind)!请参阅下一个示例
import javafx.application.Application;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class FXCards extends Application {
private class Card extends StackPane {
// we declare a property here
final BooleanProperty hideProperty = new SimpleBooleanProperty();
public Card(boolean hide) {
hideProperty.setValue(hide);
Image cardDP = new Image("http://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/52_K_di_picche.jpg/174px-52_K_di_picche.jpg");
ImageView iv = new ImageView(cardDP);
getChildren().add(iv);
Image cardBack = new Image("http://upload.wikimedia.org/wikipedia/commons/thumb/8/86/Carta_Francese_retro_Blu.jpg/174px-Carta_Francese_retro_Blu.jpg");
ImageView ivBack = new ImageView(cardBack);
getChildren().add(ivBack);
// binding to hideProperty
// card back is visible if hide property is true
ivBack.visibleProperty().bind(hideProperty);
// card front is visible if property is false, see "not()" call
iv.visibleProperty().bind(hideProperty.not());
setOnMouseClicked((e)-> {
// click on card to flip it
hideProperty.setValue(!hideProperty.getValue());
});
}
}
@Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
root.getChildren().add(new Card(true));
Scene scene = new Scene(root, 300, 500);
primaryStage.setTitle("Click to Flip!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
关于java - 如何在JavaFX中更新节点状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30196439/