我想更改按钮的样式,这里的大多数线程和互联网上的文章都显示了如何使用 Java 代码来实现,我认为这不是一个真正好的解决方案,有什么办法吗例如,仅使用 FXML(无 Css)设置一个包含一些文本和图像的按钮?
最佳答案
仅使用 fxml 的解决方案
正如 tarrsalah 所指出的,css 是推荐的执行方式,但如果您愿意,也可以在 fxml 中执行此操作:
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.text.*?>
<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml">
<children>
<Button layoutX="104.0" layoutY="81.0" mnemonicParsing="false" text="Love Potion">
<font>
<Font size="30.0" />
</font>
<graphic>
<ImageView fitHeight="150.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="http://icons.iconarchive.com/icons/mirella-gabriele/fantasy-mediaeval/128/Poison-red-icon.png" />
</image>
</ImageView>
</graphic>
</Button>
</children>
</AnchorPane>
在 SceneBuilder 中获取以上信息,将 ImageView
拖到 Button
上,它会自动设置为按钮的图形。然后选择 ImageView
并将图像的 url 输入到 SceneBuilder 属性 Pane 中 ImageView 的图像字段中。
在SceneBuilder中打开上面的fxml可以看到下图。
备用 css 属性
-fx-background*
属性的备用 css。
-fx-graphic
-fx-padding
-fx-content-display
-fx-graphic-text-gap
这些只是不同的,不一定更适合您尝试做的事情。这只是关于使用哪个的偏好。我发现这些设置比 -fx-background*
设置更易于使用。它们的限制性更强,但语法和选项对我来说更容易理解,它们的含义映射到 Labeled 的 JavaDoc API。 .
属性的详细描述在 css reference guide 中。 .
这是一个示例,其中设置了嵌入在 fxml 中的图形的样式,但最好将样式信息分离到单独的 css 样式表中,如 tarrsalah 的示例。
<Button layoutX="138.0" layoutY="226.0" mnemonicParsing="false" style="-fx-graphic: url('http://icons.iconarchive.com/icons/mirella-gabriele/fantasy-mediaeval/128/Poison-red-icon.png')" text="Love Potion">
<font>
<Font size="20.0" />
</font>
</Button>
仅使用 Java 代码向按钮添加图像的相关解决方案
关于java - 仅使用 FXML 为 JavaFX 2 按钮设置样式 - 如何将图像添加到按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16340269/