私はJavaFXで数独ゲームを作ろうとしています。 GridPaneとTextFieldを使って9x9グリッドを作った。JavaFX - GridPaneの中をクリックするとTextFieldではなくPaneが表示されます
ここで、ユーザーがその内部をクリックすると、TextFieldの背景色を変更します。すべてがうまくいることを確認するために、私はMouseEventのターゲットをプルニングしています。
私の問題は、TextFieldの中央をクリックするとターゲットがペインになり、他の場所をクリックするとターゲットが私のGridPaneになり、背景色が変わってしまうということです。
どうすればよいですか?私はそれを行う方法を理解することはできません!
public class SudokuGrid {
public static final int GRID_SIZE = 9;
private TextField[][] sudokuCells;
private GridPane sudokuGrid;
public SudokuGrid() {
sudokuCells = new TextField[GRID_SIZE][GRID_SIZE];
createSudokuGrid();
for (int row = 0; row < GRID_SIZE; row++) {
for(int col = 0; col < GRID_SIZE; col++) {
sudokuCells[row][col] = new TextField() {
@Override
public void replaceText(int start, int end, String text) {
// If the replaced text would end up being invalid, then simply
// ignore this call!
if (text.matches("[1-9]|\\s")) {
super.setText(text);
}
}
};
sudokuCells[row][col].setPrefSize(60, 60);
sudokuCells[row][col].setStyle("-fx-background-color: yellow;");
sudokuGrid.add(sudokuCells[row][col], col, row);
sudokuGrid.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
Object source = e.getTarget();
System.out.println(source);
if(source instanceof TextField) {
((TextField) source).setStyle("-fx-background-color: green;");
}
}
});
}
}
sudokuGrid.setPrefSize(270, 270); // 30 * 9
sudokuGrid.setGridLinesVisible(true);
}
private void createSudokuGrid() {
sudokuGrid = new GridPane();
for (int i = 0; i < GRID_SIZE; i++) {
RowConstraints rc = new RowConstraints();
rc.setVgrow(Priority.ALWAYS) ; // allow row to grow
rc.setFillHeight(true); // ask nodes to fill height for row
// other settings as needed...
sudokuGrid.getRowConstraints().add(rc);
ColumnConstraints cc = new ColumnConstraints();
cc.setHgrow(Priority.ALWAYS) ; // allow column to grow
cc.setFillWidth(true); // ask nodes to fill space for column
// other settings as needed...
sudokuGrid.getColumnConstraints().add(cc);
}
}
ありがとうございます。私は最後のオプションを使用しました。それは最も簡単なようです。私はこのコード 'sudokuCells [row] [col] .getStyleClass()。add(" text-field ");を追加して動作させる必要がありました。 –
@ValentinEmilCudelcuそれはそれなしで動作するはずです。 'TextField'は' text-field'というスタイルクラスを持っています(デフォルトではhttps://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html#textfield )。 (Btwは質問に答えた場合、答えを正しいものとしてマークします) –
いいえ、それがないとうまくいかない理由はありますが、助けてくれてありがとう。 –