一旦包含TableView窗格的ScrollPane附加到底部,我试图向JavaFX TabelView添加一些新行。
但即使我只添加一行,整个TableView也会刷新。 当我拥有大量数据时,这会使性能非常糟糕。
有没有办法添加单行而不重新加载之前加载的其他行?
以下是演示:
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TitledPane;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class PaneDemo extends Application {
private TableView<NodeInfo> table = new TableView<NodeInfo>();
private final ObservableList<NodeInfo> data = FXCollections.observableArrayList();
private static int index = 0;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setWidth(450);
stage.setHeight(500);
TableColumn<NodeInfo, String> firstNameCol = new TableColumn("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<NodeInfo, String>("firstName"));
TableColumn lastNameCol = new TableColumn("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<NodeInfo, String>("lastName"));
for (int i = 0; i < 5; i++) {
data.add(new NodeInfo("first Name" + index, "last Name" + index++));
}
table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol);
Button btn = new Button("add new item");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("-------------add a new row------------");
data.add(new NodeInfo("first Name" + index, "last Name" + index++));
}
});
final VBox vbox = new VBox(20);
vbox.getChildren().addAll(table, btn);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
public static class NodeInfo {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private NodeInfo(String fName, String lastName) {
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lastName);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public String getLastName() {
System.out.println(lastName.get());
return lastName.get();
}
public void setLastName(String lName) {
lastName.set(lName);
}
}
}
通过演示,控制台将通过添加新行来打印越来越多的行。
希望我足够清楚自己。