如何有条件地对按钮执行操作:
- 定义按钮的操作处理程序.
- 在操作处理程序中,测试以查看是否满足所需的条件.
- 如果测试通过,请执行所需的操作.
Short example个
final Button button = new Button(word);
button.setOnAction(e -> {
if (isRequiredWord(word)) {
button.setText(MATCHED_VALUE);
}
});
Sample application
显示带有文字的按钮网格.如果用户单击一个单词以字母"a"开头、不区分大小写的按钮,则按钮文本将从显示的单词更改为"X".
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class MatchingGameApp extends Application {
private static final String MATCHED_VALUE = "X";
private static final String[][] animalBoard = {
{ "cat", "ape" },
{ "aardvark", "dog" }
};
/**
* Add actionable buttons to a grid.
*
* @param board A 2D array of words.
* @param grid a GridPane to which buttons for each word will be added.
*/
private void addButtons(String[][] board, GridPane grid) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
final String word = board[i][j];
final Button button = new Button(word);
button.setPrefWidth(80);
button.setOnAction(e -> {
if (isRequiredWord(word)) {
button.setText(MATCHED_VALUE);
}
});
grid.add(button, i, j);
}
}
}
/**
* A required word is any word starting with a letter "a" in any case.
*/
public boolean isRequiredWord(String word) {
return word != null && !word.isEmpty() &&
word
.substring(0, 1)
.toLowerCase()
.startsWith("a");
}
@Override
public void start(Stage stage) {
GridPane layout = new GridPane(10, 10);
layout.setPadding(new Insets(10));
addButtons(animalBoard, layout);
stage.setScene(new Scene(layout));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}