尝试将Swing转换为JavaFX
这是我使用Swing时的代码片段:尝试将Swing转换为JavaFX,java,swing,javafx,Java,Swing,Javafx,这是我使用Swing时的代码片段: private static Gui gui; public static void main(String[] args){ gui = new Gui(); //(1) gui.menu(); //(2) gui.show(); //(3) } 构造函数初始化JFrame 创建JLabel和JPanel并将它们添加到框架中 将帧可见性设置为true 我一直在尝试,但使用JavaFX无法得到想要的结果。这是我最
private static Gui gui;
public static void main(String[] args){
gui = new Gui(); //(1)
gui.menu(); //(2)
gui.show(); //(3)
}
JFrame
JLabel
和JPanel
并将它们添加到框架中true
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);
}
}
–让你的课堂像这样:
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
}
}
还有更多关于您试图实现的目标的示例。作为旁白。Swing代码是错误的,因为它无法在EDT上启动GUI。代码的另一个问题是,它将
gui
成员声明为static
。不要试图在任何其他GUI工具包中复制它。取而代之的是从开始学习如何正确使用GUI工具包(Swing也应该这样做)。我投票将这个问题作为离题题结束,因为提问者应该从开始。别担心,我终于找到了正确的方法。这是出人意料的简单。不管怎样,也许我应该删除这个,你可以。