[英]Text with Icon on MenuItem JavaFx
我正在使用JavaFX进行项目。 我将FontAwesome包含在我的项目中,以避免将图像用于简单的图标。 我在一个常量类中创建了以下函数,该类生成一个带有图标和文本的HBox,这些文本将在setGraphic(Node node)
被调用。 功能如下:
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。
我的应用程序顶部有一个菜单栏,其中有Menus,其中有MenuItems。 我使用“设置” MenuItem尝试了相同的过程,但是除非光标悬停在项目上方,否则文本不会出现。
MenuItem settings = new MenuItem();
settings.setGraphic(ConstantsClass.iconText(FontAwesome.COG, "Settings")); //Obscuring name of Constants Class
此代码具有以下结果:
如何使MenuItem始终显示图标和文本?
看起来像个bug有点奇怪 。 如果图形中没有标签,则该图形似乎显示OK(例如,一个矩形似乎可以正常用作图形)。 我的猜测是CSS样式规则和菜单外观实现之间的交互有些混乱。
一种解决方法是使用快照,但是以某种方式使快照外观看起来有点粗体。
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);
}
}
也许其他人可以提出更好的解决方法(或修复)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.