gpt4 book ai didi

java - 尝试将 Swing 转换为 Java-FX

转载 作者:行者123 更新时间:2023-12-01 09:44:30 25 4
gpt4 key购买 nike

这是我使用 Swing 时的代码片段:

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
}
}

最佳答案

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

package gui;

import javafx.application.Application;


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

– 让你的类(class)像这样:

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您想要实现的目标。

关于java - 尝试将 Swing 转换为 Java-FX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38181953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com