【发布时间】:2021-06-22 22:08:51
【问题描述】:
我有一个扩展 JTable 的类。在该类中,我创建了一个填充的客户表。当我单击特定行时,我想取出该选定行的 ID 字段。
现在我的问题是,我找到的所有信息都提到使用 a
table.getColumnModel().... table.convertRowIndex ....
但在我的匿名事件 ListSelectionListener 中,我无法让它工作。它不想使用this。反映到 JTable,我不能使用表。因为那是无法识别的。
@Component
public class CustomersTable extends JTable {
private final CustomerService customerService;
public CustomersTable(CustomerService customerService) {
this.customerService = customerService;
String[] columnNames = new String[]{"Id", "Voornaam", "Achternaam", "Email", "Telefoon", "Straat", "Nummer",
"Postcode", "Stad", "Commentaar"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
this.setModel(tableModel);
List<CustomerEntity> allCustomer = this.customerService.getAllCustomer();
for (CustomerEntity entity : allCustomer) {
tableModel.addRow(entity.getForJTable());
}
// De selectie van de rij
ListSelectionModel model = this.getSelectionModel();
model.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
model.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if(!model.isSelectionEmpty()) {
// get selected row
// long id = this.getColumnModel().getColumnIndex("Id");
int selectedRow = model.getMinSelectionIndex();
// openCustomerCard(selectedRow);
}
}
});
}
}
【问题讨论】:
-
不要从
JTable扩展,这不是必需的。创建一个自定义的TableModel并将其应用于JTable的实例,这就是委托模型的重点
标签: java spring-boot swing java-11