javafx中具有不同单元格值的TableView

javafx中具有不同单元格值的TableView,javafx,tableview,cell,Javafx,Tableview,Cell,在下面的代码中有4列。在“特定值”列中,可以添加不同类型的数据,如字符串、整数、日期等。但我想在同一列中,在该单元格中输入的值旁边添加一个按钮,前提是该值为字符串 大概是这样的: 名|姓|年龄|特殊值 詹姆斯|史密斯| 10 | 10 雅各布|维斯利| 20 | abc(按钮) 安娜|萨马尔| 15 | 45.5 如何在同一列中仅为特定单元格(即包含字符串值)添加按钮 package application; import java.time.LocalDateTime; import jav

在下面的代码中有4列。在“特定值”列中,可以添加不同类型的数据,如字符串、整数、日期等。但我想在同一列中,在该单元格中输入的值旁边添加一个按钮,前提是该值为字符串

大概是这样的:

名|姓|年龄|特殊值 詹姆斯|史密斯| 10 | 10

雅各布|维斯利| 20 | abc(按钮)

安娜|萨马尔| 15 | 45.5

如何在同一列中仅为特定单元格(即包含字符串值)添加按钮

package application;

import java.time.LocalDateTime;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;

public class Main extends Application {

    private final TableView<Person<?>> tableView = new TableView<>();

    private Person<Integer> person1 = new Person<>("Jacob", "Smith", 28, 4);
    private Person<Integer> person2 = new Person<>("Isabella", "Johnson", 19, 5);
    private Person<String> person3 = new Person<>("Bob", "The Sponge", 13, "Say Hi!");
    private Person<LocalDateTime> person4 = new Person<>("Time", "Is Money", 45, LocalDateTime.now());
    private Person<Double> person5 = new Person<>("John", "Doe", 32, 457.89);

    private final ObservableList<Person<?>> data = FXCollections.observableArrayList(person1, person2, person3, person4,
            person5);

    @SuppressWarnings("unchecked")
    @Override
    public void start(Stage primaryStage) {

        TableColumn<Person<?>, String> firstNameCol = new TableColumn<>("First Name");
        firstNameCol.setMinWidth(100);
        firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));

        TableColumn<Person<?>, String> lastNameCol = new TableColumn<>("Last Name");
        lastNameCol.setMinWidth(100);
        lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));

        TableColumn<Person<?>, Integer> ageCol = new TableColumn<>("Age");
        ageCol.setMinWidth(50);
        ageCol.setCellValueFactory(new PropertyValueFactory<>("age"));

        TableColumn<Person<?>, ?> particularValueCol = new TableColumn<>("Particular Value");
        particularValueCol.setMinWidth(200);
        particularValueCol.setCellValueFactory(new PropertyValueFactory<>("particularValue"));

        tableView.setItems(data);

        // Type safety: A generic array of Table... is created for a varargs
        // parameter
        // -> @SuppressWarnings("unchecked") to start method!
        tableView.getColumns().addAll(firstNameCol, lastNameCol, ageCol, particularValueCol);

        // Output in console the selected table view's cell value/class to check
        // that the data type is correct.
        SystemOutTableViewSelectedCell.set(tableView);

        // To check that table view is correctly refreshed on data changed..
        final Button agePlusOneButton = new Button("Age +1");
        agePlusOneButton.setOnAction((ActionEvent e) -> {
            Person<?> person = tableView.getSelectionModel().getSelectedItem();
            try {
                person.setAge(person.getAge() + 1);
            } catch (NullPointerException npe) {
                //
            }
        });

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(tableView, agePlusOneButton);

        Scene scene = new Scene(new Group());
        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        primaryStage.setWidth(600);
        primaryStage.setHeight(750);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

    public static class Person<T> {

        private final StringProperty firstName;
        private final StringProperty lastName;
        private final IntegerProperty age;
        private final ObjectProperty<T> particularValue;

        private Person(String firstName, String lastName, Integer age, T particularValue) {
            this.firstName = new SimpleStringProperty(firstName);
            this.lastName = new SimpleStringProperty(lastName);
            this.age = new SimpleIntegerProperty(age);
            this.particularValue = new SimpleObjectProperty<T>(particularValue);
        }

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

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

        public StringProperty firstNameProperty() {
            return firstName;
        }

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

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

        public StringProperty lastNameProperty() {
            return lastName;
        }

        public Integer getAge() {
            return age.get();
        }

        public void setAge(Integer age) {
            this.age.set(age);
        }

        public IntegerProperty ageProperty() {
            return age;
        }

        public T getParticularValue() {
            return particularValue.get();
        }

        public void setParticularValue(T particularValue) {
            this.particularValue.set(particularValue);
        }

        public ObjectProperty<T> particularValueProperty() {
            return particularValue;
        }
    }

    public static final class SystemOutTableViewSelectedCell {
        @SuppressWarnings({ "rawtypes", "unchecked" })
        public static void set(TableView tableView) {

            tableView.getSelectionModel().setCellSelectionEnabled(true);

            ObservableList selectedCells = tableView.getSelectionModel().getSelectedCells();

            selectedCells.addListener(new ListChangeListener() {
                @Override
                public void onChanged(Change c) {
                    TablePosition tablePosition = (TablePosition) selectedCells.get(0);
                    Object val = tablePosition.getTableColumn().getCellData(tablePosition.getRow());
                    System.out.println("Selected Cell (Row: " + tablePosition.getRow() + " / Col: "
                            + tablePosition.getColumn() + ") Value: " + val + " / " + val.getClass());
                }
            });
        }
    }

}
包应用;
导入java.time.LocalDateTime;
导入javafx.application.application;
导入javafx.beans.property.IntegerProperty;
导入javafx.beans.property.ObjectProperty;
导入javafx.beans.property.SimpleIntegerProperty;
导入javafx.beans.property.SimpleObject属性;
导入javafx.beans.property.SimpleStringProperty;
导入javafx.beans.property.StringProperty;
导入javafx.collections.FXCollections;
导入javafx.collections.ListChangeListener;
导入javafx.collections.ObservableList;
导入javafx.event.ActionEvent;
导入javafx.geometry.Insets;
导入javafx.stage.stage;
导入javafx.scene.Group;
导入javafx.scene.scene;
导入javafx.scene.control.Button;
导入javafx.scene.control.TableColumn;
导入javafx.scene.control.TablePosition;
导入javafx.scene.control.TableView;
导入javafx.scene.control.cell.PropertyValueFactory;
导入javafx.scene.layout.VBox;
公共类主扩展应用程序{
private final TableView>data=FXCollections.observableArrayList(person1、person2、person3、person4、,
个人5);
@抑制警告(“未选中”)
@凌驾
公共无效开始(阶段primaryStage){
TableColumn,String>lastNameCol=newtableColumn(“姓氏”);
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(新属性ValueFactory(“lastName”));
TableColumn,?>SpecialValueCol=新的TableColumn(“特殊值”);
特殊值设置最小宽度(200);
SpecificularValueCol.setCellValueFactory(新属性值工厂(“SpecificularValueFactory”));
tableView.setItems(数据);
//类型安全性:为varargs创建表…的通用数组
//参数
//->@SuppressWarnings(“未选中”)以启动方法!
tableView.getColumns().addAll(firstNameCol、lastNameCol、ageCol、specificularvaluecol);
//在控制台中输出要检查的选定表视图的单元格值/类
//数据类型是否正确。
SystemOutTableViewSelectedCell.set(tableView);
//检查表视图是否在数据更改时正确刷新。。
最终按钮年龄plusonebutton=新按钮(“年龄+1”);
agePlusOneButton.setOnAction((ActionEvent e)->{
Person=tableView.getSelectionModel().getSelectedItem();
试一试{
person.setAge(person.getAge()+1);
}捕获(NullPointerException npe){
//
}
});
最终VBox VBox=新的VBox();
vbox.setspace(5);
设置填充(新的插入(10,0,0,10));
vbox.getChildren().addAll(tableView,agePlusOneButton);
场景=新场景(新组());
((组)scene.getRoot()).getChildren().addAll(vbox);
初级阶段。设置宽度(600);
初生阶段。设定高度(750);
初级阶段。场景(场景);
primaryStage.show();
}
公共静态void main(字符串[]args){
发射(args);
}
公共静态类人员{
私有财产名;
私有财产姓氏;
私人最终综合财产年龄;
私有最终对象属性特殊值;
私人(字符串名、字符串名、整数年龄、T特殊值){
this.firstName=新的SimpleStringProperty(firstName);
this.lastName=新的SimpleStringProperty(lastName);
this.age=新的SimpleIntegerProperty(age);
this.particularValue=新的SimpleObject属性(particularValue);
}
公共字符串getFirstName(){
返回firstName.get();
}
public void setFirstName(字符串firstName){
this.firstName.set(firstName);
}
public StringProperty firstNameProperty(){
返回名字;
}
公共字符串getLastName(){
返回lastName.get();
}
public void setLastName(字符串lastName){
this.lastName.set(lastName);
}
公共StringProperty lastNameProperty(){
返回姓氏;
}
公共整数getAge(){
returnage.get();
}
公共无效设置(整数期限){
此.age.set(年龄);
}
公共IntegerProperty ageProperty(){
回归年龄;
}
公共T getSpecificularValue(){
返回specialValue.get();
}
public void设置特殊值(T特殊值){
this.particularValue.set(particularValue);
}
public ObjectProperty SpecialValueProperty(){
返回特定值;
}
}
公共静态最终类SystemOutTableViewSelectedCell{
@SuppressWarnings({“rawtypes”,“unchecked”})
公共静态无效集(TableView TableView){
tableView.getSelectionModel().setCellSelectionEnabled(true);
ObservableList selectedCells=tableView.getSelectionModel().getSelectedCells();
selectedCells.addListener(新ListChangeListener(){
@凌驾
更改后的公共作废(更改c){
TablePosition TablePosition=(TablePosition)selectedCells.get(0);
Object val=tablePosition.getTableColumn().getCellData(tablePosition.getRow());
System.out.println(“Sele
TableColumn<Person<?>, Object> particularValueCol = new TableColumn<>("Particular Value");
particularValueCol.setMinWidth(200);
particularValueCol.setCellValueFactory(new PropertyValueFactory<>("particularValue"));

particularValueCol.setCellFactory(tc -> new TableCell<Person<?>, Object>() {
    private Button button = new Button("A button");

    @Override
    protected void updateItem(Object item, boolean empty) {
        super.updateItem(item, empty) ;
        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            setText(item.toString());
            if (item instanceof String) {
                setGraphic(button);
            } else {
                setGraphic(null);
            }
        }
    }
});