[英]How to refer to actual clicked button in event handler in java fx?
事實是,我有二維按鈕陣列,我想向每個按鈕動態添加setOnClick方法,這會改變它們的文本,這是一個問題,因為我不能在其中使用變量,例如myArray [i ] [j],因此實際上我無法引用我的按鈕。
我從您的兩個想法中都使用了一點,對此我非常感謝。 我動態創建了按鈕,還使用了新類擴展按鈕類來為按鈕添加水平和垂直值。 現在看起來像這樣:
package sample;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("Hello World");
GridPane root = new GridPane();
primaryStage.setScene(new Scene(root, 1000, 600));
MyButton[][] buttonArray = new MyButton[10][10];
HBox[] hboxArray = new HBox[10];
for(int i=0;i<10;i++)
{
hboxArray[i]=new HBox();
for(int j=0;j<10;j++)
{
MyButton button =new MyButton(i,j);
button.setMinSize(100,50);
buttonArray[i][j]=button;
button.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
button.setText("button"+button.getH()+","+button.getV());
//where getH is get horizontal and getV is get vertical
button.setDisable(true);
}
});
hboxArray[i].getChildren().add(buttonArray[i][j]);
}
}
for(int i=0;i<10;i++)
{
root.add(hboxArray[i],1,i);
}
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
如果我沒看錯您的問題,這個小應用程序將顯示一個示例,說明如何完成您要嘗試執行的操作。 該應用程序將Button
存儲到2D Array
。 它還會創建一個Action Listener
為每個當改變文本按鈕Button
被按下。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* @author Sedrick
*/
public class JavaFXApplication extends Application {
@Override
public void start(Stage primaryStage) {
Button [][] buttonContainer = new Button[3][3];
VBox vbox = new VBox();
for(int i = 0; i < 3; i++)
{
for(int t = 0; t < 3; t++)
{
Button button = new Button();
button.setText("button" + i + " : " + t);
//Create event handler
button.setOnAction((event)->{
button.setText("Hello World!");
});
buttonContainer[i][t] = button;//Add the current button to the Button 2D array
vbox.getChildren().add(buttonContainer[i][t]);//Add current button to the VBox
}
}
StackPane root = new StackPane();
root.getChildren().add(vbox);
Scene scene = new Scene(root, 500, 500);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
一種方法:為每個按鈕添加一個不同的onAction處理程序,而不是在所有按鈕上設置相同的onAction處理程序。
另一種方法:覆蓋Button並添加實例變量以保存按鈕的行/列:button [i] [j] = new MyButton(i,j,...); 並為行和列添加吸氣劑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.