javafx - 从控制器类外部调用的 gridpane.getchildren().add() 会阻止程序
问题描述
我正在制作一个传统的日本棋盘游戏(类似于围棋)。我想做的是通过从类外调用控制器类中的方法将图像放在 GridPane(15*15) 的正方形中。但是,当执行“gomokuBoard.getChildren().add(imageview);”时,控制器程序会阻塞。在对手_put_stone() 方法中。为了从控制器程序外部放置控制对象,我应该怎么做?
以下是我已经做过的。我注释掉了这行代码并执行了程序。除了对手的棋子没有出现在 GUI 屏幕上之外,它的结果是成功的。
这是控制器类的一部分。我提到的那一行是“opponent_put_stone”方法的最后一行。
//this method is called by pushing a button in GridPane. this method works.
@FXML private GridPane gomokuBoard;
@FXML private Button hint_button;
@FXML private Label messagefromServer;
@FXML private static Button[][] put_stone_button;
private EventHandler<MouseEvent> mouseClick;
private Image black_stone;
private Image white_stone;
private static int mycolor = 1;
private GomokuGame game;
public void put_mystone(MouseEvent event) {
int x = GridPane.getRowIndex((Node) event.getSource());
int y = GridPane.getColumnIndex((Node) event.getSource());
put_stone_button[x][y].setDisable(true);
game.gomoku.putStone(x, y, mycolor);
GomokuGame.go_signal();
ImageView imageview;
if(mycolor == 1) {
imageview = new ImageView(black_stone);
}
else {
imageview = new ImageView(white_stone);
}
GridPane.setConstraints(imageview, y, x);
gomokuBoard.getChildren().add(imageview);
game.x = x;
game.y = y;
}
//this method is called from outside the controller program.
public void opponent_put_stone(int x, int y) {
put_stone_button[x][y].setDisable(true);
game.gomoku.putStone(x, y, 3-mycolor);
ImageView imageview;
if(mycolor == 1) {
imageview = new ImageView(white_stone);
}
else {
imageview = new ImageView(black_stone);
}
GridPane.setConstraints(imageview, y, x);
gomokuBoard.getChildren().add(imageview); //this line blocks program
}
解决方案
我通过使用 Platform.runLater() 解决了这个问题。由于GUI只能在应用程序线程中操作,问题就出现了。
推荐阅读
- javascript - 如何水平折叠 react-bootstrap 手风琴面板?
- python - Improve speed by creating dynamic columns in a Dataframe
- c - 如何验证指定的内存地址是否已分配
- botframework - Bot Framework 错误:操作返回了无效的状态代码“0”
- c# - 确定是否将从 MassTransit 3 中的观察者上下文重试消息
- python-3.x - 如何在python中将多列变成键值列表
- c# - 打破内部异步方法而不打破内部尝试捕获
- google-api - Google Vault API HttpError 500“遇到内部错误。”
- r - 如何解释来自 ddplyr::mutate 的列长度错误?
- c# - 使用登录标头重定向到辅助站点