本文介绍了如何设置和获取JavaFX Table的单元格值(如swing JTable)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaFX的新手,想知道如何设置和获取JavaFX表的单元格值,例如Swing JTable.即setValueAt()& JavaFX表中Swing JTablegetValueAt.

I am new to JavaFX and would like to know how to set and get the cell value of JavaFX Table like Swing JTable. i.e. an alternative of setValueAt() & getValueAt of Swing JTable in JavaFX Table.

//would like to get the index of column by Name    
int index_RunnableQueueItem = tableQueue.getColumns().indexOf("RunnableQueueItem");
//would like to get the selected row
int row = tableQueue.getSelectionModel().getSelectedIndex();
if (index_RunnableQueueItem != -1 && row != -1) {
// would like to get the value at index of row and column.

//Update that value and set back to cell. 

}     

推荐答案

TableView确实不支持此方法.

TableView really doesn't support this methodology.

这是使用反射来做您想要的事的一种较脆弱的方法.这完全取决于您在单元格值工厂中使用PropertyValueFactory,以便它可以查找属性名称.

Here's a somewhat brittle means of doing what you want, using reflection. It's entirely dependent upon you using PropertyValueFactory in your cell value factory so it can lookup the property name, though.

class MyItem
{
    SimpleStringProperty nameProperty = new SimpleStringProperty("name");
    public MyItem(String name) {
        nameProperty.set(name);
    }
    public String getName() { return nameProperty.get(); }
    public void setName(String name) { nameProperty.set(name); }
    public SimpleStringProperty getNameProperty() { return nameProperty; }
}

...

TableView<MyItem> t = new TableView<MyItem>();
TableColumn col = new TableColumn("Name Header");
col.setCellValueFactory(new PropertyValueFactory<MyItem, String>("name"));
t.getColumns().addAll(t);

...

public void setValue(int row, int col, Object val)
{
    final MyItem selectedRow = t.getItems().get(row);
    final TableColumn<MyItem,?> selectedColumn = t.getColumns().get(col);
    // Lookup the propery name for this column
    final String propertyName =   ((PropertyValueFactory)selectedColumn.getCellValueFactory()).getProperty();
    try 
    {
        // Use reflection to get the property
        final Field f = MyItem.class.getField(propertyName);
        final Object o = f.get(selectedRow);

        // Modify the value based on the type of property
        if (o instanceof SimpleStringProperty)
        {
            ((SimpleStringProperty)o).setValue(val.toString());
        }
        else if (o instanceof SimpleIntegerProperty)
        {
            ...
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

这篇关于如何设置和获取JavaFX Table的单元格值(如swing JTable)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 23:11