JavaFX15中TableView有泛型限制而JavaFX8版本没有。
关于这个问题国内解答较少所以我有了写本篇的想法,我参考了JavaFX15的文档,成功地解决了这个问题。
ProductColumnItem.java
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class ProductColumnItem {
private StringProperty name;
private LongProperty price;
public ProductColumnItem(String name, long price) {
setName(name);
setPrice(price);
}
public StringProperty nameProperty() {
if (this.name == null) this.name = new SimpleStringProperty(this, "name");
return this.name;
}
public LongProperty priceProperty() {
if (this.price == null) this.price = new SimpleLongProperty(this, "price");
return this.price;
}
public void setName(String name) {
nameProperty().set(name);
}
public void setPrice(Long price) {
priceProperty().set(price);
}
public String getName() {
return nameProperty().get();
}
public Long getPrice() {
return priceProperty().get();
}
}
MainApp.java
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class MainApp extends Application {
/*
* The main() method is ignored in correctly deployed JavaFX application. main()
* serves only as fallback in case the application can not be launched through
* deployment artifacts, e.g., in IDEs with limited FX support. NetBeans ignores
* main().
*
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
List<ProductColumnItem> labelData = List.of(
new ProductColumnItem("pen", 2),
new ProductColumnItem("knife", 10)
);
ObservableList<ProductColumnItem> labelDataMembers = FXCollections.observableArrayList(labelData);
TableView<ProductColumnItem> tableView = new TableView<>();
tableView.setItems(labelDataMembers);
TableColumn<ProductColumnItem, String> nameColumn = new TableColumn<>("name");
nameColumn.setCellValueFactory(new PropertyValueFactory<>(labelData.get(0).nameProperty().getName()));
TableColumn<ProductColumnItem, Long> priceColumn = new TableColumn<>("price");
priceColumn.setCellValueFactory(new PropertyValueFactory<>(labelData.get(0).priceProperty().getName()));
tableView.getColumns().setAll(nameColumn, priceColumn);
StackPane root = new StackPane();
Scene scene = new Scene(root, 300, 400);
root.getChildren().add(tableView);
stage.setScene(scene);
stage.setTitle("hello");
stage.show();
}
}
效果图: