2016-07-04 32 views
0

這是我的代碼片段時,我使用的Swing:試圖擺動轉換成Java-FX

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(); 
} 

桂類:

package gui; 

import javafx.application.Application; 


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

,有你的類是這樣的:如下

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

順便說一句。 Swing代碼是錯誤的,因爲它無法啓動EDT上的GUI。代碼的另一個問題是它將'gui'成員聲明爲'static'。 **不要**嘗試在任何其他GUI工具包中複製它。請從[JavaFX入門](http://docs.oracle.com/javafx/2/get_started/jfxpub-get_started.htm)開始學習如何正確使用GUI工具包(您還應該*完成*完成與Swing)。 –

+2

我正在投票結束這個問題,因爲提問者***應該從[JavaFX入門]開始(http://docs.oracle.com/javafx/2/get_started/jfxpub- get_started.htm)。 –

+0

別擔心,我終於找出了應該完成的正確方法。這非常容易。無論如何,也許我應該刪除這個 – user3157517

回答

1

最簡單的方法是使用Application.launch:

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 mange to reach this part, there will be some null pointer 
    //exception, well everything looks real initialised to me 
    } 
} 

有更多的樣品here你想要實現的。