首页 > 解决方案 > 按钮没有响应 javaFx

问题描述

这些按钮不提供控制台输出。两个按钮位于 BorderPane 底部的 Vbox 中,按下时应打印“new”或“continue”。

我遵循了一个教程并尝试将其扩展到另一个按钮。

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application implements EventHandler<ActionEvent> {

    Button btn1, btn2;

    public static void main(String[] args) {
        launch(args);
    }

    public void start(Stage primaryStage) throws Exception {

        primaryStage.setTitle("title");

        Button btn1 = new Button("new");
        Button btn2 = new Button ("continue");

        btn1.setOnAction(this);
        btn2.setOnAction(this);

        VBox vb = new VBox (btn1, btn2);
        vb.setSpacing(10);
        vb.setPadding(new Insets(20));

        BorderPane root = new BorderPane();
        root.setBottom(vb);

        Scene scene = new Scene (root, 300, 250);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    @Override
    public void handle(ActionEvent event) {

        if (event.getSource()==btn1) {  
            System.out.println("new!");
        } else if (event.getSource()==btn2) {  
            System.out.println("continue!");
        }
    }
}   

什么也没发生,但应该有“新的或继续”的输出

标签: javabuttonjavafx

解决方案


从按钮中删除类。

这样,代码将使用字段中的按钮,而不是创建新按钮。

public void start(Stage primaryStage) throws Exception {
  primaryStage.setTitle("title");

  btn1 = new Button("new");
  btn2 = new Button ("continue");
  // the rest of the code will be the same
}

推荐阅读