我想知道如何将 JTable 的选定行放入模型中。
现在我得到了这样的东西。
int selectedRowIndex = tabelSpelers.getSelectedRow();
int selectedColumnIndex = tabelSpelers.getColumnCount();
Object[] tableData = new Object[selectedColumnIndex];
for (int j = 0 ; j < selectedColumnIndex; j++){
tableData[j] = tabelSpelers.getValueAt(selectedRowIndex,j);
}
Speler selectedSpeler = (Speler) tableData;
JOptionPane.showMessageDialog(this, tableData);
模型看起来像这样:
public Speler(int speler_id, String voornaam, String achternaam, String adres, String postcode, String woonplaats, String telefoonnummer, String email, int rating, boolean isBekend)
最佳答案
在没有更多信息的情况下,您最好的选择是明确的手动翻译。而不是:
Object[] tableData = new Object[selectedColumnIndex];
for (int j = 0 ; j < selectedColumnIndex; j++){
tableData[j] = tabelSpelers.getValueAt(selectedRowIndex,j);
}
Speler selectedSpeler = (Speler) tableData;
这会在最后一行产生 ClassCastException,您可以这样写:
Speler selectedSpeler = new Speler();
selectedSpeler.setFoo(tabelSpelers.getValueAt(selectedRowIndex, 1));
selectedSpeler.setBar(tabelSpelers.getValueAt(selectedRowIndex, 2));
依此类推,填充 selectedSpeler 对象的每个属性。
但是,您可能更喜欢 extend AbstractTableModel as in this example直接用 Speler 对象支持您的 table 。
关于Java 将 object[] 转换为模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27778000/