2

我是javafx的新手。任何人都可以帮我在 TableView 标题上添加一些 TextFields。在 css 集成的帮助下,我尝试将 TableView 放在堆栈窗格上并将文本字段放在其上方。不能成功。

4

1 回答 1

4

是的,你可以这样做。

对于 JavaFX 2.2

在 JavaFX 2.2 (jdk7u6+) 中实现了 jira RT-14909,它允许您在列上设置图形(任意节点)以指定列的表头。

TableColumn col = new TableColumn("");
TextField colHeaderTextField = new TextField("Pink Elephants");
col.setGraphic(colHeaderTextField);

对于 JavaFX 2.0 和 2.1

将表格添加到活动场景并渲染后,您可以查找表格标题标签并更改它们以显示图形(可以是任何类型的节点),该图形显示表格标题的文本字段而不是默认值静态标签文本。

这是一个示例:

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class TableWithTextHeaders extends Application {
  public static void main(String[] args) { launch(args); }

  @Override public void start(Stage stage) {
    TableColumn firstNameCol = new TableColumn("First Name");
    firstNameCol.setCellValueFactory(new PropertyValueFactory<Person,String>("firstName"));
    TableColumn lastNameCol = new TableColumn("Last Name");
    lastNameCol.setCellValueFactory(new PropertyValueFactory<Person,String>("lastName"));

    TableView table = new TableView();
    table.getColumns().addAll(firstNameCol, lastNameCol);
    table.setItems(FXCollections.observableArrayList(
      new Person("Jacob", "Smith"),
      new Person("Isabella", "Johnson"),
      new Person("Ethan", "Williams")
    ));
    table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

    StackPane layout = new StackPane();
    layout.setStyle("-fx-padding: 10;");
    layout.getChildren().add(table);
    Scene scene = new Scene(layout);
    stage.setScene(scene);
    stage.show();

    for (Node n: table.lookupAll(".column-header > .label")) {
      if (n instanceof Label) {
        Label label = (Label) n;
        TextField textField = new TextField(label.getText());
        label.textProperty().bind(textField.textProperty());
        label.setGraphic(textField);
        label.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
      }
    }
  }  

  public static class Person {
    private final SimpleStringProperty firstName;
    private final SimpleStringProperty lastName;

    private Person(String fName, String lName) {
      this.firstName = new SimpleStringProperty(fName);
      this.lastName = new SimpleStringProperty(lName);
    }

    public String getFirstName() { return firstName.get(); }
    public void setFirstName(String fName) { firstName.set(fName); }
    public String getLastName() { return lastName.get(); }
    public void setLastName(String fName) { lastName.set(fName); }
  }
}
于 2012-05-10T00:30:20.553 回答