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

时间:2017-04-21 06:29:25

标签: java button javafx event-handling javafx-8

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

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

2 个答案:

答案 0 :(得分:2)

它被称为动态添加节点(按钮)。你可以用这种方法练习。

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。

答案 1 :(得分:0)

您不必在按钮处理程序中有一个按钮处理程序,如果Button b仅在单击Button a后显示,则可以添加另一个Button b处理程序(在{{1}之外)处理程序),Button a如果不可见

,则无法触发点击事件
相关问题