首页 > 解决方案 > 从控制器类外部调用的 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
    }

标签: javafx

解决方案


我通过使用 Platform.runLater() 解决了这个问题。由于GUI只能在应用程序线程中操作,问题就出现了。


推荐阅读