它被称为动态添加节点(按钮)。你可以用这种方法练习。
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class JavaFXApplication91 extends Application
{
int idControl = 0;
@Override
public void start(Stage primaryStage)
{
VBox root = new VBox();
Button btn = new Button();
btn.setText("Add New Button");
btn.setId("Button " + idControl);
btn.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
idControl++;
Button tempButton = new Button();
tempButton.setText("Button " + idControl);
tempButton.setId("Button " + idControl);
tempButton.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event2)
{
System.out.println("You clicked: " + ((Button)event2.getSource()).getId());
}
});
root.getChildren().add(tempButton);
}
});
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
此应用程序在启动时创建一个按钮。如果你点击按钮,它会创建一个新的按钮。点击每个新按钮时,显示被点击的按钮的ID。
我不明白这个问题。完全按照你想要做的事情,并为按钮b创建事件处理程序有什么问题? – Mark
这个问题可能是由于尝试将'Button'实例分配给Button []'数组引起的,编译器会在消息中告诉您编译错误。 – fabian