【问题标题】:Trying to convert Swing to Java-FX尝试将 Swing 转换为 Java-FX
【发布时间】:2016-07-04 10:04:44
【问题描述】:

这是我使用 Swing 时的代码的 sn-p:

private static Gui gui;

public static void main(String[] args){
    gui = new Gui(); //(1)
    gui.menu();      //(2)
    gui.show();      //(3)
}
  1. 构造函数初始化JFrame
  2. 创建JLabelJPanel 并将它们都添加到框架中。
  3. 将框架可见性设置为true

我一直在尝试,但无法使用 Java-FX 获得我想要的结果。这是我最后一次尝试的样子:

private static Gui gui;

public static void main(String[] args){
    gui = new Gui();
    Application.launch(Gui.class, args);
    gui.menu();
    gui.show();
}

GUI类:

private static Stage stage;

public class Gui extends Application {

    publc void start(Stage primaryStage){

    Gui.stage = primaryStage;
    stage.setTitle("title");

    //I read that some method blocking is involved here, I want to go back!
    }

    public void menu(){

    BorderPane abc = new BorderPane();
    Scene scene = new Scene(abc, 200, 200);
    stage.setScene(scene);

    //if I somehow mange to reach this part, there will be some null pointer
    //exception, well everything looks real initialised to me
    }

    public void show(){

    stage.show();

    //I have never reach this part
    }
}

【问题讨论】:

  • 顺便说一句。 Swing 代码是错误的,因为它无法在 EDT 上启动 GUI。代码的另一个问题是它将gui 成员声明为static不要尝试在任何其他 GUI 工具包中复制它。而是从Getting Started with JavaFX 开始并学习如何正确使用 GUI 工具包(您应该使用 Swing 完成一些事情)。
  • 我投票决定将此问题作为题外话结束,因为提问者应该Getting Started with JavaFX开头。
  • 别着急,我终于找到了正确的做法。这出乎意料地容易。无论如何,也许我应该删除这个

标签: java swing javafx


【解决方案1】:

最简单的方法是使用Application.launch(_:_:),如下:

package gui;

import javafx.application.Application;


public class NewClass {
    public static void main(String[] args) {
        Application.launch(Gui.class, args);
    }
}

– 让你的班级像这样:

package gui;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class Gui extends Application {
    private Scene scene;
    private Stage stage;
    
    @Override
    public void start(Stage stage) {
        this.stage = stage;
        Button btn = new Button("test");
        this.scene = new Scene(btn, 200, 250);
        stage.setTitle("title");
        stage.setScene(scene);
        stage.show();
    }
    
    public void menu() {
        BorderPane abc = new BorderPane();
        this.scene = new Scene(abc, 200, 200);
        this.stage.setScene(scene);

        // If I somehow manage to reach this part, there will be a NullPointerException
        // Everything looks real initialised to me
    }
}

有更多示例 here 您正在尝试实现的目标。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 2015-08-15
    • 1970-01-01
    相关资源
    最近更新 更多