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
生成一副牌。
问题是:当我对特定hide
实例使用setHide()
时,GUI不会反映Card
状态的更改。
这让我相信构造函数没有做它应该做的事情或者GUI需要别的东西才能理解它需要在卡面朝下时显示替代图片。在任何一种情况下,我需要做些什么才能在GUI中反映出变化?
答案 0 :(得分:2)
每次只调用构造函数一次时,您需要更新状态。在JavaFX中执行它的很酷的方法是使用proprety绑定!见下一个例子
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);
}
}