如果你已經在你的控制器設置所有的按鈕,你可以這樣做:
//I supposed you named you 'button_a' your
@FXML
Button button_a;
@Override
public void initialize(URL location, ResourceBundle resources) {
button_a.setOnAction(event->{
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("file.txt")); //or new File("c:/users/.../.../file.txt");
writer.write(button_a.getText()); //will give the letter you write on the button : the letter of the keyboard
} catch (IOException e) {
System.err.println("IOError on write");
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println("IOError on close");
e.printStackTrace();
}
}
}
});
}
一個簡單的方法可能是:你一定把所有的按鈕在一個容器中,一個GridPane會很好,因爲你可以把所有的東西放到一個容器中(並且只放置按鈕,或者你需要在循環中每次檢查它是一個按鈕),然後遍歷GridPane的子節點(按鈕):
@FXML
GridPane grid;
@Override
public void initialize(URL location, ResourceBundle resources) {
String fileName = "test.txt";
for(Node button : grid.getChildren()){
((Button)button).setOnAction(event->{
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(fileName)); //or new File("c:/users/.../.../file.txt");
writer.write(((Button)button).getText()); //will give the letter you write on the button : the letter of the keyboard
} catch (IOException e) {
System.err.println("IOError on write");
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println("IOError on close");
e.printStackTrace();
}
}
}
});
}
}
希望這會有幫助