如何在ControlsFX Notification通知中实现部分文本加粗等差异化样式?
解决方案
ControlsFX 的 Notifications 组件支持通过 graphic() 方法传入任意 JavaFX 节点作为通知内容,你可以基于这个特性实现局部文本样式自定义,不需要依赖 text() 方法和全局CSS。
实现代码示例
import org.controlsfx.control.Notifications; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.scene.text.FontWeight; import javafx.scene.text.Font; // 分段构建文本,分别设置样式 Text prefix = new Text("This is "); Text boldContent = new Text("bold text"); // 给指定文本设置加粗样式 boldContent.setFont(Font.font("System", FontWeight.BOLD, 12)); // 可按需扩展其他样式,比如修改颜色、斜体等 Text suffix = new Text(" with custom style"); suffix.setFill(javafx.scene.paint.Color.RED); // 组装TextFlow TextFlow notificationContent = new TextFlow(prefix, boldContent, suffix); // 按需设置宽度适配通知弹窗尺寸 notificationContent.setPrefWidth(300); // 显示通知 Notifications.create() .title("My Title") .graphic(notificationContent) // 注意不要调用text()方法,避免出现重复内容 .showInformation();
补充说明
- 如果需要更复杂的内容布局,可以替换
TextFlow为VBox、HBox等任意布局容器,支持图文混排、多段落不同样式等需求 - 可以直接对
TextFlow或内部的Text节点设置行内CSS,调整行间距、内边距等属性:
notificationContent.setStyle("-fx-line-spacing: 3; -fx-padding: 2 0;");
内容的提问来源于stack exchange,提问作者wand555
相关产品推荐
相关产品推荐

