gpt4 book ai didi

java - MenuItem JavaFx 上带有图标的文本

转载 作者:行者123 更新时间:2023-11-30 07:55:25 26 4
gpt4 key购买 nike

我正在使用 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。

我的应用程序顶部有一个菜单栏,里面有菜单,还有菜单项。我用“设置”MenuItem 尝试了相同的过程,但除非光标位于该项目上,否则文本不会出现。

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

如何让 MenuItem 始终显示图标和文本?

最佳答案

有点奇怪,它看起来像 bug .如果图形中没有标签,则图形似乎显示正常(例如,矩形似乎可以作为图形正常工作)。我的猜测是 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);
}
}

也许其他人可以提出更好的解决方法(或修复)。

关于java - MenuItem JavaFx 上带有图标的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43214334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com