【发布时间】:2016-11-24 01:47:47
【问题描述】:
我正在创建一个迷你游戏,其中包含一组标签,这些标签一开始是黑色的,但一旦被点击就会变成黄色。我想要发生的是当当前单击的标签变为黄色时,先前单击的标签变回黑色。
我遇到的问题是如何将之前点击的标签变回黑色。每次单击标签并使用不同的类做不同的事情时,我都尝试创建一个新的GridPane,但都没有奏效。我还尝试在创建 GridPane 时创建一个二维标签数组,但我无法使用它来重置以前的标签。
这是我的代码,我哪里出错了?
package application;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.InputEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
BorderPane borderpane = new BorderPane();
GridPane grid = setGrid();
borderpane.setTop(grid);
Scene sc = new Scene(borderpane, 400, 400);
sc.getStylesheets().add("application/application.css");
primaryStage.setScene(sc);
primaryStage.show();
}
public GridPane setGrid() {
GridPane grid = new GridPane();
for (int row = 0; row < 5; row++)
for (int col = 0; col < 5; col++) {
Label l = new Label();
l.setPrefHeight(100);
l.setPrefWidth(100);
l.getStyleClass().add("box");
l.setOnMouseClicked(new EventHandler<InputEvent>() {
@Override
public void handle(InputEvent arg0) {
l.getStyleClass().add("clicked");
}
});
grid.add(l, col, row);
}
return grid;
}
public static void main(String[] args) {
Application.launch(args);
}
}
【问题讨论】:
标签: java javafx labels gridpane