Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 初始化后更改TableView中文本的字体_Java_Fonts_Javafx_Tableview - Fatal编程技术网

Java 初始化后更改TableView中文本的字体

Java 初始化后更改TableView中文本的字体,java,fonts,javafx,tableview,Java,Fonts,Javafx,Tableview,我想更改我的表格视图中文本的字体,但是当我这样尝试时,它没有应用字体,因为它找不到任何节点: tableView.lookupAll(".table-row-cell").forEach(cell -> { applyFont(cell, MainFont.LIGHT, FontStyle.SUBHEAD); }); 其中,applyFont()是一个自定义函数。我认为这与未初始化的TableView有关,所以我尝试将其包装在平台.runLater()中,但这也不起作用 但是,唯

我想更改我的
表格视图中文本的字体,但是当我这样尝试时,它没有应用字体,因为它找不到任何节点:

tableView.lookupAll(".table-row-cell").forEach(cell -> {
    applyFont(cell, MainFont.LIGHT, FontStyle.SUBHEAD);
});
其中,
applyFont()
是一个自定义函数。我认为这与未初始化的
TableView
有关,所以我尝试将其包装在
平台.runLater()
中,但这也不起作用

但是,唯一有效的方法是将此代码放在侦听器中(选择、悬停等):

当我现在将鼠标悬停在
TableView
上时,字体会发生变化。但我不明白为什么它不能与
Platform.runLater()
一起工作

此代码位于我的应用程序中每个屏幕的超类中,在构建子屏幕后运行,但尚未显示

我错过了什么?非常感谢您的帮助

注意:我不能在我的情况下使用CSS解决方案。

问题 您想设置TableView的字体样式。您要设置行/单元格的字体样式

解决方案 您可以使用TableView类的方法
setStyle()
。使用,您可以看到哪些设置是可能的。这是CSS,但是没有额外的CSS文件,所以你可以用任何方式来做

更改TableView单元格的字体样式 A将如下所示:

import java.util.Set;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TableFontStyle extends Application {

  @Override
  public void start(Stage primaryStage) {
    ObservableList<Person> persons
            = FXCollections.observableArrayList(
                    new Person("Sir", "Tobey"),
                    new Person("Admiral", "von Schneider"),
                    new Person("Mr.", "Pommeroy"),
                    new Person("Mr.", "Winterbottom"));

    TableView<Person> tableView = new TableView<>(persons);

    TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
    firstNameCol.setCellValueFactory(new PropertyValueFactory("firstName"));
    TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
    lastNameCol.setCellValueFactory(new PropertyValueFactory("lastName"));

    tableView.getColumns().setAll(firstNameCol, lastNameCol);
    tableView.getSelectionModel().clearAndSelect(0);

    Button btn = new Button("Change Font Style");
    btn.setOnAction((e) -> {
      Set<Node> cells = tableView.lookupAll(".table-cell");
      cells.forEach((c) -> {
        c.setStyle("-fx-font-weight:lighter;-fx-font-style:italic;");
      });
    });

    VBox root = new VBox();
    root.getChildren().addAll(tableView, btn);

    Scene scene = new Scene(root, 300, 250);
    primaryStage.setTitle("Font Table");
    primaryStage.setScene(scene);
    primaryStage.show();
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    launch(args);
  }

  public class Person {

    private final StringProperty firstName
            = new SimpleStringProperty(this, "firstName");

    public void setFirstName(String value) {
      firstNameProperty().set(value);
    }

    public String getFirstName() {
      return firstNameProperty().get();
    }

    public StringProperty firstNameProperty() {
      return firstName;
    }

    private final StringProperty lastName
            = new SimpleStringProperty(this, "lastName");

    ;

    public void setLastName(String value) {
      lastNameProperty().set(value);
    }

    public String getLastName() {
      return lastNameProperty().get();
    }

    public StringProperty lastNameProperty() {
      return lastName;
    }

    public Person(String firstName, String lastName) {
      this.firstName.set(firstName);
      this.lastName.set(lastName);
    }
  }
}
import java.util.Set;
导入javafx.application.application;
导入javafx.beans.property.SimpleStringProperty;
导入javafx.beans.property.StringProperty;
导入javafx.collections.FXCollections;
导入javafx.collections.ObservableList;
导入javafx.scene.Node;
导入javafx.scene.scene;
导入javafx.scene.control.Button;
导入javafx.scene.control.TableColumn;
导入javafx.scene.control.TableView;
导入javafx.scene.control.cell.PropertyValueFactory;
导入javafx.scene.layout.VBox;
导入javafx.stage.stage;
公共类TableFontStyle扩展了应用程序{
@凌驾
公共无效开始(阶段primaryStage){
观察者
=FXCollections.observableArrayList(
新人(“先生”、“托比”),
新人(“海军上将”、“冯·施耐德”),
新人(“先生”,“波默罗伊”),
新人(“先生”,“温特巴顿”);
TableView TableView=新的TableView(人);
TableColumn firstNameCol=新的TableColumn(“名字”);
firstNameCol.setCellValueFactory(新属性ValueFactory(“firstName”));
TableColumn lastNameCol=新的TableColumn(“姓氏”);
lastNameCol.setCellValueFactory(新属性ValueFactory(“lastName”));
tableView.getColumns().setAll(firstNameCol,lastNameCol);
tableView.getSelectionModel().clearAndSelect(0);
按钮btn=新按钮(“更改字体样式”);
btn.设定动作((e)->{
Set cells=tableView.lookupAll(“.table cell”);
单元格。forEach((c)->{
c、 setStyle(“-fx字体重量:较轻;-fx字体样式:斜体;”);
});
});
VBox root=新的VBox();
root.getChildren().addAll(tableView,btn);
场景=新场景(根,300,250);
setTitle(“字体表”);
初级阶段。场景(场景);
primaryStage.show();
}
/**
*@param指定命令行参数
*/
公共静态void main(字符串[]args){
发射(args);
}
公共阶层人士{
私有最终属性名
=新的SimpleStringProperty(即“名字”);
public void setFirstName(字符串值){
firstNameProperty().set(值);
}
公共字符串getFirstName(){
返回firstNameProperty().get();
}
public StringProperty firstNameProperty(){
返回名字;
}
私有最终StringProperty lastName
=新的SimpleStringProperty(此“姓氏”);
;
public void setLastName(字符串值){
lastNameProperty().set(值);
}
公共字符串getLastName(){
返回lastNameProperty().get();
}
公共StringProperty lastNameProperty(){
返回姓氏;
}
公众人物(字符串名、字符串名){
this.firstName.set(firstName);
this.lastName.set(lastName);
}
}
}
工作应用程序将如下所示:

import java.util.Set;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TableFontStyle extends Application {

  @Override
  public void start(Stage primaryStage) {
    ObservableList<Person> persons
            = FXCollections.observableArrayList(
                    new Person("Sir", "Tobey"),
                    new Person("Admiral", "von Schneider"),
                    new Person("Mr.", "Pommeroy"),
                    new Person("Mr.", "Winterbottom"));

    TableView<Person> tableView = new TableView<>(persons);

    TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
    firstNameCol.setCellValueFactory(new PropertyValueFactory("firstName"));
    TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
    lastNameCol.setCellValueFactory(new PropertyValueFactory("lastName"));

    tableView.getColumns().setAll(firstNameCol, lastNameCol);
    tableView.getSelectionModel().clearAndSelect(0);

    Button btn = new Button("Change Font Style");
    btn.setOnAction((e) -> {
      Set<Node> cells = tableView.lookupAll(".table-cell");
      cells.forEach((c) -> {
        c.setStyle("-fx-font-weight:lighter;-fx-font-style:italic;");
      });
    });

    VBox root = new VBox();
    root.getChildren().addAll(tableView, btn);

    Scene scene = new Scene(root, 300, 250);
    primaryStage.setTitle("Font Table");
    primaryStage.setScene(scene);
    primaryStage.show();
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    launch(args);
  }

  public class Person {

    private final StringProperty firstName
            = new SimpleStringProperty(this, "firstName");

    public void setFirstName(String value) {
      firstNameProperty().set(value);
    }

    public String getFirstName() {
      return firstNameProperty().get();
    }

    public StringProperty firstNameProperty() {
      return firstName;
    }

    private final StringProperty lastName
            = new SimpleStringProperty(this, "lastName");

    ;

    public void setLastName(String value) {
      lastNameProperty().set(value);
    }

    public String getLastName() {
      return lastNameProperty().get();
    }

    public StringProperty lastNameProperty() {
      return lastName;
    }

    public Person(String firstName, String lastName) {
      this.firstName.set(firstName);
      this.lastName.set(lastName);
    }
  }
}

问题 您想设置TableView的字体样式。您要设置行/单元格的字体样式

解决方案 您可以使用TableView类的方法
setStyle()
。使用,您可以看到哪些设置是可能的。这是CSS,但是没有额外的CSS文件,所以你可以用任何方式来做

更改TableView单元格的字体样式 A将如下所示:

import java.util.Set;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TableFontStyle extends Application {

  @Override
  public void start(Stage primaryStage) {
    ObservableList<Person> persons
            = FXCollections.observableArrayList(
                    new Person("Sir", "Tobey"),
                    new Person("Admiral", "von Schneider"),
                    new Person("Mr.", "Pommeroy"),
                    new Person("Mr.", "Winterbottom"));

    TableView<Person> tableView = new TableView<>(persons);

    TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
    firstNameCol.setCellValueFactory(new PropertyValueFactory("firstName"));
    TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
    lastNameCol.setCellValueFactory(new PropertyValueFactory("lastName"));

    tableView.getColumns().setAll(firstNameCol, lastNameCol);
    tableView.getSelectionModel().clearAndSelect(0);

    Button btn = new Button("Change Font Style");
    btn.setOnAction((e) -> {
      Set<Node> cells = tableView.lookupAll(".table-cell");
      cells.forEach((c) -> {
        c.setStyle("-fx-font-weight:lighter;-fx-font-style:italic;");
      });
    });

    VBox root = new VBox();
    root.getChildren().addAll(tableView, btn);

    Scene scene = new Scene(root, 300, 250);
    primaryStage.setTitle("Font Table");
    primaryStage.setScene(scene);
    primaryStage.show();
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    launch(args);
  }

  public class Person {

    private final StringProperty firstName
            = new SimpleStringProperty(this, "firstName");

    public void setFirstName(String value) {
      firstNameProperty().set(value);
    }

    public String getFirstName() {
      return firstNameProperty().get();
    }

    public StringProperty firstNameProperty() {
      return firstName;
    }

    private final StringProperty lastName
            = new SimpleStringProperty(this, "lastName");

    ;

    public void setLastName(String value) {
      lastNameProperty().set(value);
    }

    public String getLastName() {
      return lastNameProperty().get();
    }

    public StringProperty lastNameProperty() {
      return lastName;
    }

    public Person(String firstName, String lastName) {
      this.firstName.set(firstName);
      this.lastName.set(lastName);
    }
  }
}
import java.util.Set;
导入javafx.application.application;
导入javafx.beans.property.SimpleStringProperty;
导入javafx.beans.property.StringProperty;
导入javafx.collections.FXCollections;
导入javafx.collections.ObservableList;
导入javafx.scene.Node;
导入javafx.scene.scene;
导入javafx.scene.control.Button;
导入javafx.scene.control.TableColumn;
导入javafx.scene.control.TableView;
导入javafx.scene.control.cell.PropertyValueFactory;
导入javafx.scene.layout.VBox;
导入javafx.stage.stage;
公共类TableFontStyle扩展了应用程序{
@凌驾
公共无效开始(阶段primaryStage){
观察者
=FXCollections.observableArrayList(
新人(“先生”、“托比”),
新人(“海军上将”、“冯·施耐德”),
新人(“先生”,“波默罗伊”),
新人(“先生”,“温特巴顿”);
TableView TableView=新的TableView(人);
TableColumn firstNameCol=新的TableColumn(“名字”);
firstNameCol.setCellValueFactory(新属性ValueFactory(“firstName”));
TableColumn lastNameCol=新的TableColumn(“姓氏”);
lastNameCol.setCellValueFactory(新属性ValueFactory(“lastName”));
tableView.getColumns().setA
import java.util.function.Function;

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;

public class ConfigurableFontTable extends Application {

    private StringProperty fontFamily = new SimpleStringProperty(Font.getDefault().getFamily());
    private ObjectProperty<FontWeight> fontWeight = new SimpleObjectProperty<>(FontWeight.NORMAL);
    private BooleanProperty italic = new SimpleBooleanProperty();
    private IntegerProperty fontSize = new SimpleIntegerProperty((int)Font.getDefault().getSize());

    private ObjectProperty<Color> fontFill = new SimpleObjectProperty<>(Color.BLACK);

    private StringProperty style = new SimpleStringProperty();

    @Override
    public void start(Stage primaryStage) {
        style.bind(Bindings.createStringBinding(() -> String.format(
                "-fx-font-family: %s;\n"
                + "-fx-font-weight: %d;\n"
                + "-fx-font-style: %s;\n"
                + "-fx-font-size: %d;\n"
                + "-fx-text-background-color: rgba(%d, %d, %d, %f);\n",
                fontFamily.get(),
                fontWeight.get().getWeight(),
                italic.get()?"italic":"normal",
                fontSize.get(),
                (int)(255 * fontFill.get().getRed()),
                (int)(255 * fontFill.get().getGreen()),
                (int)(255 * fontFill.get().getBlue()),
                fontFill.get().getOpacity()
            ),
            fontFamily,
            fontWeight,
            italic,
            fontSize,
            fontFill
        ));

        TableView<Person> table = new TableView<>();
        table.setRowFactory(tv -> {
            TableRow<Person> row = new TableRow<>();
            row.styleProperty().bind(style);
            return row ;
        });

        table.getColumns().add(column("First Name", Person::firstNameProperty));
        table.getColumns().add(column("Last Name", Person::lastNameProperty));
        table.getColumns().add(column("Email", Person::emailProperty));

        table.getItems().addAll(
                new Person("Jacob", "Smith", "jacob.smith@example.com"),
                new Person("Isabella", "Johnson", "isabella.johnson@example.com"),
                new Person("Ethan", "Williams", "ethan.williams@example.com"),
                new Person("Emma", "Jones", "emma.jones@example.com"),
                new Person("Michael", "Brown", "michael.brown@example.com")
        );

        Button changeStyleButton = new Button("Change style...");
        changeStyleButton.setOnAction(e -> showChangeStyleDialog(primaryStage));

        BorderPane root = new BorderPane(table, null, null, changeStyleButton, null);
        BorderPane.setAlignment(changeStyleButton, Pos.CENTER);
        BorderPane.setMargin(changeStyleButton, new Insets(10));

        primaryStage.setScene(new Scene(root, 800, 600));
        primaryStage.show();
    }

    private void showChangeStyleDialog(Stage owner) {
        GridPane root = new GridPane();
        root.setHgap(5);
        root.setVgap(5);
        root.setPadding(new Insets(10));

        ColumnConstraints leftCol = new ColumnConstraints();
        leftCol.setHalignment(HPos.RIGHT);
        leftCol.setHgrow(Priority.NEVER);

        ColumnConstraints rightCol = new ColumnConstraints();

        root.getColumnConstraints().addAll(leftCol, rightCol);

        ComboBox<String> fontFamilyChoice = new ComboBox<>();
        fontFamilyChoice.getItems().addAll(Font.getFamilies());
        fontFamilyChoice.setValue(fontFamily.get());

        ComboBox<FontWeight> fontWeightChoice = new ComboBox<>();
        fontWeightChoice.getItems().addAll(FontWeight.values());
        fontWeightChoice.setValue(fontWeight.get());

        CheckBox italicCheckBox = new CheckBox("Italic");
        italicCheckBox.setSelected(italic.get());

        ComboBox<Integer> fontSizeChoice = new ComboBox<>();
        fontSizeChoice.getItems().addAll(4, 6, 8, 10, 12, 16, 20, 24, 32, 40, 48);
        fontSizeChoice.setValue(fontSize.get());

        ColorPicker colorPicker = new ColorPicker();
        colorPicker.setValue(fontFill.get());

        root.addRow(0,  new Label("Font:"), fontFamilyChoice);
        root.addRow(1, new Label("Weight:"), fontWeightChoice);
        root.addRow(2, new Label("Size:"), fontSizeChoice);
        root.add(italicCheckBox, 1, 3);
        root.addRow(4, new Label("Text Color:"), colorPicker);

        Stage stage = new Stage();

        Button okButton = new Button("OK");
        okButton.setOnAction(e -> {
            fontFamily.set(fontFamilyChoice.getValue());
            fontWeight.set(fontWeightChoice.getValue());
            fontSize.set(fontSizeChoice.getValue());
            italic.set(italicCheckBox.isSelected());
            fontFill.set(colorPicker.getValue());
            stage.hide();
        });

        Button cancelButton = new Button("Cancel");
        cancelButton.setOnAction(e -> stage.hide());

        HBox buttons = new HBox(5, okButton, cancelButton);
        buttons.setAlignment(Pos.CENTER);
        root.add(buttons, 0, 5, 2, 1);

        stage.initOwner(owner);
        stage.setScene(new Scene(root));
        stage.show();
    }

    private static <S,T> TableColumn<S,T> column(String title, Function<S, ObservableValue<T>> property) {
        TableColumn<S,T> col = new TableColumn<>(title);
        col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
        return col ;
    }

    public class Person {
        private final StringProperty firstName = new SimpleStringProperty(this,"firstName");
        private final StringProperty lastName = new SimpleStringProperty(this, "lastName");
        private final StringProperty email = new SimpleStringProperty(this, "email");

        public Person(String firstName, String lastName, String email) {
            this.firstName.set(firstName);
            this.lastName.set(lastName);
            this.email.set(email);
        }

        public final StringProperty firstNameProperty() {
            return this.firstName;
        }

        public final String getFirstName() {
            return this.firstNameProperty().get();
        }

        public final void setFirstName(final String firstName) {
            this.firstNameProperty().set(firstName);
        }

        public final StringProperty lastNameProperty() {
            return this.lastName;
        }

        public final String getLastName() {
            return this.lastNameProperty().get();
        }

        public final void setLastName(final String lastName) {
            this.lastNameProperty().set(lastName);
        }

        public final StringProperty emailProperty() {
            return this.email;
        }

        public final String getEmail() {
            return this.emailProperty().get();
        }

        public final void setEmail(final String email) {
            this.emailProperty().set(email);
        }

    }

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