2017-06-20 74 views
1

我想製作一個程序,如果用戶點擊菜單項,我們可以改變場景。javafx菜單上的點擊事件

Simple image of the program

例如如果u點擊菜單欄的設置,在同一個窗口中的另一個場景將出現,並且您可以更改程序的設置。

注意:我的菜單沒有任何菜單項。只是菜單欄。

到目前爲止我試過了什麼? 向HBox添加一些按鈕並將其分配到BorderPane的頂部。它確實有效,但看起來不像菜單。嘗試使它看起來像CSS菜單,但沒有奏效。

什麼問題? 問題是主菜單上的點擊處理程序不起作用。 如果我從單擊事件處理程序從開始按鈕它確實工作,但不是在「設置」菜單上。

想知道實現這個想法的最好方法是什麼?

+0

菜單不產生事件,如果它們是空的(不幸)。大概你最好的選擇是向HBox(或「ToolBar」)添加一些按鈕(或者可能只是標籤?),並將它們設置爲菜單形式,就像你描述的那樣。如果你不能按照你想要的方式工作,我建議嘗試這個方法,併發佈一個具體的問題,試圖完成這項工作。 –

回答

1

下面是我的以前的項目的部分。 MenuItem在不同的類中,我調用main方法來切換場景。

我有兩個頁面選擇和信息,都有自己的容器,場景和樣式表。選擇頁面是開始時顯示的初始頁面,我切換信息頁面。

settingsMenuItem.setOnAction(e -> { 
    e.consume(); 
    Launcher.selectionPage(); 
}); 

我的主類:

public class Launcher extends Application { 

    private static FlowPane selectionPane; 
    private static BorderPane infoPane; 
    private static Scene selectionScene, infoScene; 
    private static Stage theStage; 
    private static String selectionCSS; 
    private static String informationCSS; 

    public static void main(String args[]) { 
     launch(args); 
    } 

    @Override 
    public void start(Stage primaryStage) throws Exception { 

     //Global reference needed to switch scenes in another method. 
     this.theStage = primaryStage; 

     //Declares resources, in this case stylesheet. Declared here to be applied in another method 
     selectionCSS = this.getClass().getResource("/views/SelectionStyle.css").toExternalForm(); 
     informationCSS = this.getClass().getResource("/views/InformationStyle.css").toExternalForm(); 

     //Initial page setup 
     selectionPane = new SelectionPage(); 
     selectionScene = new Scene(selectionPane, 500, 500); 
     selectionScene.getStylesheets().add(selectionCSS); 

     //Stage setup 
     primaryStage.setScene(selectionScene); 
     primaryStage.show(); 
    } 


    //Changes page 
    public static void informationPage(String starSign) { 

     infoPane = new InformationPage(); 
     infoScene = new Scene(infoPane, 500, 270); 
     infoScene.getStylesheets().add(informationCSS); 
     theStage.setScene(infoScene); 
    } 
}