我最近在学习JavaFX,有一个关于如何刷新面板的问题。在这个简单的程序中,我希望黑色正方形在我点击移动按钮时向右移动到下一个块中,但它没有起作用,我想知道如何修复我的代码。
主类:
public class Main extends Application {
private Cell cells[] = new Cell[5];
private Player player;
private Board board;
Button move = new Button("move");
public Main() throws Exception {
for (int i = 0; i < cells.length; i++) {
cells[i] = new Cell(i);
}
this.player = new Player(0, cells);
this.board = new Board(player, cells);
}
@Override
public void start(Stage primaryStage) throws Exception {
Main game = new Main();
BorderPane pane = new BorderPane();
pane.setCenter(board);
pane.setBottom(move);
Scene scene = new Scene(pane,400,80);
primaryStage.setTitle("Move");
primaryStage.setScene(scene);
primaryStage.show();
move.setOnAction(e -> game.move());
}
public void move() {
player.currentCell.index += 1;
board.paint();
}
public static void main(String[] args) {
launch(args);
}
}
板(Board)类:
class Board extends Pane {
private Player player;
public Cell cells[];
private final int CELLWIDTH = 40;
private final int CELLHEIGHT = 40;
private final int LMARGIN = 100;
public Board(Player p, Cell cells[]) {
player = p;
this.cells = cells;
paint();
}
public void paint() {
Cell cell;
for (int i=0; i<cells.length; i++) {
cell = cells[i];
Rectangle r1 = new Rectangle(xCor(cell.index), 0, CELLWIDTH, CELLHEIGHT);
r1.setStroke(Color.BLACK);
r1.setFill(Color.WHITE);
getChildren().add(r1);
}
cell = player.currentCell;
Rectangle r2 = new Rectangle(xCor(cell.index), 0, CELLWIDTH, CELLHEIGHT);
r2.setFill(Color.BLACK);
getChildren().add(r2);
}
private int xCor(int col) {
return LMARGIN + col * CELLWIDTH;
}
}
玩家类:
class Player {
public int position;
public Cell currentCell;
public Player(int position, Cell cell[]) throws Exception {
this.currentCell = cell[0];
}
}
单元格类:
class Cell {
public int index;
public Cell(int index) {
this.index = index;
}
}
Main
实例?应该是move.setOnAction(e -> this.move());
。此外,您正在不断向Board
添加更多的Rectangle
,但从未将它们删除。这是有意为之吗? - fabian