本文介绍了正确地从(已排序的)JTable获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我已经开发了一个基本的自定义JTableModel,如下所示

I have developed a basic custom JTableModel as follows

public class CustomTableModel extends DefaultTableModel {
  List<MyClass> data;
  public CustomTableModel(List<MyClass> data) {
    this.data = data;
  }

  public Class<?> getColumnClass(int columnIndex) {
    return MyClass.class;
  }

  public MyClass getValueAt(int rowIndex, int columnIndex) {
    return data.get(rowIndex);
  }

  // ...
}



I then use a basic custom JTableCellRenderer as follows

public class CustomTableCellRenderer extends JLabel implements TableCellRenderer {

  public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int column) {

    MyClass myClass = (MyClass)value;

    lbl.setText(myClass.getString());

    return this;
  }
}

我还有一个自定义JPanel,显示各种信息跟随

I also have a custom JPanel that displays various information as follows

public class MyPanel extends JPanel {
  private MyClass myClass;

  public MyPanel(MyClass myClass) {
    // initialize components
  }

  public setMyClass(MyClass myClass) {
    this.myClass = myClass;
    updateFields();
  }

  private void updateFields() {
    this.fieldString.setText(myClass == null ? "" : myClass.getString());
    // ...
  }
}

最后,我使用表格列出我的数据和自定义面板以显示所选数据的详细信息。

Finally, I use a table to list my data and the custom panel to display the details of the selected data.

public class JCustomFrame extends JFrame {
  public JCustomFrame(List<MyClass> data) {
    // ...
    JTable table = new JTable(new CustomTableModel(data));
    table.setDefaultRenderer(MyClass.class, new CustomTableCellRenderer());

  }
}

我想要完成的是从表获取所选的MyClass,无论排序

我尝试了ListSelectionListener,但方法不返回除选定索引之外的任何内容。即使我有索引,如果表被排序,我的模型也不那么复杂,并且会返回错误的对象。

I tried ListSelectionListener but the methods do not return anything other than the selected indexes. Even if I have the index, if the table is sorted, my model is not so sophisticated and will return the wrong object.

推荐答案

您必须使用:

使用该索引,您可以访问您的表模型,看看您需要的对象是什么。

With that index you can access your table model and see what's the object you need.

注意 Java 1.6中引入了表格排序和此方法

Note Table sorting along with this method was introduced in Java 1.6

这篇关于正确地从(已排序的)JTable获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 11:54