2017-04-04 99 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); 
    } 
} 

也许别人能想出一个更好的解决办法(或修复)。