2017-04-04 102 views
2

我正在使用JavaFX的項目上工作。我在我的項目中包含了FontAwesome,以避免使用簡單圖標的圖像。我在一個常量類中創建了以下函數,該函數生成一個HBox,其中的圖標和文本將在setGraphic(Node node)中調用。該函數如下:MenuItem上帶有圖標的文本JavaFx

public static HBox iconText(String icon, String text) { 
    return ConstantsClass.iconText(icon, text, 5); 
} 

public static HBox iconText(String icon, String text, int spacing) { 
    HBox box = new HBox(spacing); 
    Label iconLabel = new Label(icon); 
    iconLabel.setFont(ConstantsClass.fontAwesome); 
    Label textLabel = new Label(text); 
    box.getChildren().addAll(iconLabel, textLabel); 
    return box; 
} 

的方法完美地工作的按鈕,諸如具有帶箭頭圖標返回按鈕。但它似乎並沒有在MenuItems上工作。

我有一個菜單欄在我的應用程序的頂部,其中菜單,和MenuItems在那些。我用「設置」菜單項嘗試了相同的過程,但除非光標位於項目上方,否則文本不會顯示。

MenuItem settings = new MenuItem(); 
settings.setGraphic(ConstantsClass.iconText(FontAwesome.COG, "Settings")); //Obscuring name of Constants Class 

此代碼有以下結果:

When the user just clicks on the menu drop down

When the user hovers over the Menu Item

我怎樣才能讓菜單項始終顯示圖標和文本?

+1

爲什麼要使用HBox?爲什麼不將[設置菜單項文本](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/MenuItem.html#setText-java.lang.String-)設置爲文本和[菜單項圖形](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/MenuItem.html#setGraphic-javafx.scene.Node-)到您的圖像(在你的情況FontAwesome標籤)? – jewelsea

+0

出於好奇,你嘗試過'新MenuItem(「\ u2699設置」)或'新MenuItem(「\ u26ed設置」)'而不是使用自定義字體嗎? – VGR

+0

@jewelsea謝謝你的建議,這似乎是一個更有效的方法來解決這個問題。但是,這仍然取得了相同的結果。 – JoseRivas1998

回答

3

這有點奇怪,它看起來像一個bug。如果圖形中沒有標籤,圖形似乎顯示OK(例如,矩形似乎可以正常工作,如圖形)。我的猜測是CSS樣式規則和菜單皮膚實現之間的交互是一種混亂。

解決方法是使用快照,但不知何故使得快照在外觀上略顯粗體。

broken broken highlight fixed snapshot

import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.SnapshotParameters; 
import javafx.scene.control.*; 
import javafx.scene.image.*; 
import javafx.scene.layout.VBox; 
import javafx.scene.paint.Color; 
import javafx.scene.shape.Rectangle; 
import javafx.stage.Stage; 

public class MenuDisplay extends Application { 
    public void start(Stage stage) throws Exception { 
     Label label = new Label("(*)"); 
     label.setStyle("-fx-background-color: null;"); 
     Scene dummyScene = new Scene(label, Color.TRANSPARENT); 
     SnapshotParameters params = new SnapshotParameters(); 
     params.setFill(Color.TRANSPARENT); 
     Image snapshot = label.snapshot(params, null); 
     ImageView imageView = new ImageView(snapshot); 

     Menu menu = new Menu("Choices"); 
     menu.getItems().addAll(
      new MenuItem("Broken Label Graphic", new Label("(*)")), 
      new MenuItem("OK Rect", new Rectangle(16, 16, Color.FORESTGREEN)), 
      new MenuItem("Fixed Snapshot", imageView) 
     ); 
     MenuBar menuBar = new MenuBar(menu); 

     Scene scene = new Scene(
       new VBox(menuBar), 100, 100 
     ); 

     stage.setScene(scene); 
     stage.show(); 
    } 

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

也許別人能想出一個更好的解決辦法(或修復)。