java - 按钮没有响应 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!");
}
}
}
什么也没发生,但应该有“新的或继续”的输出
解决方案
从按钮中删除类。
这样,代码将使用字段中的按钮,而不是创建新按钮。
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
}
推荐阅读
- c++ - WINAPI 窗口未显示
- git - 在 git 中的两个标签之间拉取请求
- javascript - 在 React 中将类组件转换为功能组件
- java - 有没有办法设置 Ignite 瘦客户端类加载器?
- powershell - 在 pscustomobject 中重复一个值
- swift - 无法在 ios 设备上模拟推送通知
- python - 使用带有 python 代码的屏幕管理器切换屏幕
- python - 无法在python中安装pptk
- python - 是否可以在没有 exec() 的情况下自动使模块的所有公共类方法成为全局函数?以turtle.py为例
- xaml - UWP XAML 智能感知 DataTemplate.DataType