【问题标题】:How to change the color of the placeholder text in JavaFX TableView?如何更改 JavaFX TableView 中占位符文本的颜色?
【发布时间】:2018-02-26 18:53:05
【问题描述】:

我相信这很简单,虽然我还想不通:
如何更改 JavaFX TableView 中占位符文本的颜色?

这是占位符文本,如果表格为空,则会显示:

【问题讨论】:

标签: tableview javafx-8 placeholder


【解决方案1】:

有(至少)两种方法可以解决这个问题。

通过 CSS

咨询JavaFx Css Reference,您会看到,TableView 有一个内部占位符,您可以使用 Css 来解决。

如果文档不足或者您需要更多有关场景图结构的信息,请使用ScenicView 进行探索。

通过占位符节点

咨询JavaFx 8 Api documentation 会发现,有一个 placeholder 属性,允许您将自定义节点设置为占位符。

演示

此演示展示了这两种方法:

TableViewPlaceholderFill.java

package application;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;

public class TableViewPlaceholderFill extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        TableView<String> tableViaCss = new TableView<>();
        tableViaCss.getStyleClass().add("my-little-pony");

        TableView<String> tableWithCustomPlaceholder = new TableView<>();
        final Label placeholderLabel = new Label
                ("Hello, Kitty!");
        placeholderLabel.setFont(Font.font("monospace", FontWeight.BLACK, 16));
        placeholderLabel.setTextFill(Color.HOTPINK);
        tableWithCustomPlaceholder.setPlaceholder(new StackPane(placeholderLabel));

        Scene scene = new Scene(new HBox(4,tableViaCss,
                tableWithCustomPlaceholder));
        scene.getStylesheets().add(TableViewPlaceholderFill.class
                .getResource("application.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

application.css

.my-little-pony {
     -fx-background-color: palevioletred;
 }

 .my-little-pony .placeholder .label {
     -fx-text-fill: linen;
     -fx-font-family: 'serif';
     -fx-font-size: 1.666em;
     -fx-font-weight: bold;
 }

【讨论】:

  • 我使用第二种方法实现了它,现在运行良好,谢谢。只需注意一件事:如果以编程方式设置占位符,则必须使用正确类型的节点。我最初使用的是Text 节点而不是Label,它不适用于Text(即使在CSS 中寻址.text)。
  • Text 应该可以正常工作。请记住,它继承了Shape 的形式,因此属性名称不同。
猜你喜欢
  • 2019-12-09
  • 2014-06-10
  • 2017-05-18
  • 2013-02-04
  • 1970-01-01
  • 2010-11-23
  • 1970-01-01
  • 2015-01-29
相关资源
最近更新 更多