尝试从JavaFX中的表视图中选择单行时遇到了一些问题。
以下是我使用数据库中的数据填充表格的方法:
public void populateCategoryTable() {
data = FXCollections.observableArrayList();
try {
db.getConnection();
String sql = "SELECT * FROM sm_category";
ResultSet rs = null;
// Call readRequest to get the result
rs = db.readRequest(sql);
while (rs.next()) {
ObservableList<String> row = FXCollections.observableArrayList();
//All the rows are added here dynamically
row.add(rs.getString("categoryID"));
data.add(row);
}
viewCategory.setItems(data);
rs.close();
} catch (SQLException ex) {
ex.printStackTrace();
System.out.println("Error SQL!!!");
System.exit(0);
}
TableColumn id = new TableColumn("ID");
id.setVisible(false);
id.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(0).toString());
}
});
viewCategory.getColumns().addAll(id);
TableView.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //Error here
TableView.TableViewSelectionModel selectionModel = viewCategory.getSelectionModel();
ObservableList selectedCells = selectionModel.getSelectedCells();
TablePosition tablePosition = (TablePosition) selectedCells.get(0);
int row = tablePosition.getRow(); // yields the row that the currently selected cell is in
}
但是,当我尝试插入setSelectionMode代码时,出现错误。它告诉我找不到符号 symbol:方法setSelectionMode(int) location:class TableView
我记得当我在JavaSwing中创建表时,我用它来为表设置模型:DefaultTableModel tableModel =(DefaultTableModel)jTable.getModel();
但是,我不能在javaFX中这样做。有人可以帮我解决这个问题吗?
提前致谢。
答案 0 :(得分:0)
tableview的默认选择模式为SelectionMode.SINGLE
。要将其更改为多次尝试
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
&gt; 我要做的是从表中选择一行并获取索引
获取所选索引:
viewCategory.getSelectionModel().getSelectedIndex();
收听索引的变化:
viewCategory.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("index changed from " + oldValue + " to " + newValue);
}
});