【问题标题】:Java Swing extends JTable anonymouse classJava Swing 扩展了 JTable 匿名类
【发布时间】: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


【解决方案1】:
// long id = this.getColumnModel().getColumnIndex("Id");

“this”指的是您的 ListSelectionListener 的实例。

要访问 JTable 的实例,您可以使用:

JTable table = CustomersTable.this;

但这不是最好的设计。不要扩展 JTable。

只应在向类添加功能时扩展类。创建 TableModel 或添加监听器并不是添加功能。

阅读 How to Use Tables 上的 Swing 教程部分。 TableFilterDemo 展示了如何使用 ListSelectionListener。

现在我的问题是我找到的所有信息都提到使用 table.getColumnModel()....

没有必要使用列模型。您从 TableModel 中获取数据:

int row = table.getSelectedRow();
long id = table.getModel().getValueAt(row, 0);

table.convertRowIndex ....

您只需要在对表格进行排序或过滤时使用该方法,但是为了安全起见,使用该方法是一种很好的做法:

int row = table.convertRowIndexToModel( table.getSelectedRow() );
long id = table.getModel().getValueAt(row, 0);

【讨论】:

  • @RicBocad,很高兴它有帮助。不要忘记通过单击复选标记“接受”答案。请参阅:What should I do when someone answers my question。我也希望你花时间重新设计你的代码,而不仅仅是修复你的编译错误。
  • 呵呵,我已尽我所知编辑了我的代码。然而,当我将类加载到我更大的项目中时,我确实留下了扩展 JTable,作为一个表并且仅作为一个表。
【解决方案2】:

还要考虑JTable有自己的getValueAt(int row, int column)方法;使用这种方法你不需要使用convertRowIndexToModel(int row);此外,由于 JTable 具有移动列的能力,因此您还应该转换列索引,但再一次,使用 JTable.getValueAt(int row, int column) 没有问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    相关资源
    最近更新 更多