Javafx:按钮处理程序中的按钮处理程序


Button a=new Button();
...
a.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent e)
{
Button []b=new Button();
...
}
});     

单击按钮 a 后,将显示其他按钮 b。我想为按钮 b 创建一个事件处理程序。我该怎么办?

这称为动态添加节点(按钮)。您可以使用此方法进行练习。

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。

您不必在按钮处理程序中具有按钮处理程序,如果Button b仅在单击Button a后显示,则可以添加另一个Button b处理程序(Button a处理程序外部),Button b如果单击事件不可见,则不能不触发 Click 事件

最新更新