【问题标题】:Javafx: button handler in a button handlerJavafx:按钮处理程序中的按钮处理程序
【发布时间】:2017-04-21 06:29:24
【问题描述】:
Button a=new Button();
...
a.setOnAction(new EventHandler<ActionEvent>()
    {
        public void handle(ActionEvent e)
        {
             Button []b=new Button();
         ...
        }
    });     

点击按钮a后,会出现其他按钮b。我想为按钮 b 创建一个事件处理程序。我该怎么办?

【问题讨论】:

  • 我不明白这个问题。完全按照您的意愿为按钮 b 创建事件处理程序有什么问题?
  • 该问题可能是由于尝试将Button 实例分配给Button[] 数组引起的,编译器会在编译错误消息中告诉您。

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


【解决方案1】:

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

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。

【讨论】:

    【解决方案2】:

    您不必在按钮处理程序中包含按钮处理程序,如果 Button b 仅在单击 Button a 后出现,您可以添加另一个 Button b 处理程序(在 Button a 处理程序之外),Button b 不能如果不可见,则不触发点击事件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多