[英]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.