我有问题,不知道如何解决。
我有按钮,我需要在右侧的文本旁边添加图像。我做到了,但在调整此按钮的大小后,图像总是在文本旁边。有什么解决方案可以让按钮的左侧文本和图像右侧? (就像来自scenebuilder的截图)
FXML 代码:
<Button fx:id="btn1" alignment="BASELINE_LEFT" contentDisplay="RIGHT" maxHeight="-Infinity" maxWidth="1.7976931348623157E308" mnemonicParsing="false" prefHeight="50.0" text="Text">
<graphic>
<ImageView fitHeight="24.0" fitWidth="24.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="/images/User/user.png" preserveRatio="false" smooth="false" />
</image>
</ImageView>
</graphic>
</Button>
最佳答案
背景
一般来说,我建议,只需在按钮上使用 ContentDisplay 并让按钮代表您管理按钮内项目的布局。但是这种方法不适用于您的特定用例。
sample 溶液
将文本和图像都放在您自己的布局管理器(例如 HBox)中的图形中。通过这种方式,您可以灵活地将自定义布局应用于按钮,从而使您可以完全按照自己的意愿放置文本和图像。
在示例解决方案中,我在文本和图形之间添加了一个 Pane ,其 hgrow 约束为 always,以便 Pane 将充当文本和图像之间的可扩展的隐形间隔物,将它们水平推开尽可能远是可能的(在整体按钮大小的限制内)。
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="150.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Button contentDisplay="RIGHT" mnemonicParsing="false" prefHeight="98.0" prefWidth="259.0" style="-fx-base: thistle;">
<graphic>
<HBox alignment="CENTER" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mouseTransparent="true">
<children>
<Label text="Nightshade">
<font>
<Font name="Papyrus" size="24.0" />
</font></Label>
<Pane HBox.hgrow="ALWAYS" />
<ImageView>
<image>
<Image url="@Potion-icon.png" />
</image>
</ImageView>
</children>
</HBox>
</graphic>
</Button>
</children>
</StackPane>
关于javafx - 带有图像的按钮(使用 FXML/CSS 进行样式设置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34852751/