jTable row count VS model row count

限于喜欢 提交于 2019-12-20 07:21:56

问题


I have a jTable which loads data from a DB query This load produces 32 results, thus 32 rows in the TableModel With myTable.getRowCount() i correctly get 32

Then i create a new empty model and load it into the table After that, if i call myTable.getRowCount() i still get 32 But if i call myModel.getRowCount() i correctly get 0!

Why there should be difference between table.getRowCount() and model.getRowCount() if my table is using the model?

...
System.out.println(myTable.getRowCount());  // 32


String[] columnNames= {null};
DefaultTableModel emptyModel= new DefaultTableModel(null, columnNames);
emptyModel.setRowCount(0);
myTable.setModel(emptyModel);

System.out.println(myTable.getRowCount());  // still 32, expecting 0
System.out.println(emptyModel.getRowCount());  // 0 as expected

回答1:


When using a custom RowSorter (or any RowSorter for that matter), one must take care to make sure the models of the sorter and the table always match. As specified in the setRowSorter Javadoc:

If the underlying model of the RowSorter differs from that of this JTable undefined behavior will result.

The setModel method of the JTable will not update the row sorter, unless you are using a default automatic one (by setting the autoCreateRowSorter flag).

As such, you should

  • keep a reference to your sorter and update its model as well
    OR
  • use the default row sorter by setting setAutoCreateRowSorter(true) on your table and not a custom one,



回答2:


Can you post a verifiable code of yours? because i tried with the following code and the model changed without any issues.

  public static void main(String[] args) throws InterruptedException {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        DefaultTableModel model = new DefaultTableModel(
                new Object[][] { { "some", "text" }, { "any", "text" },
                        { "even", "more" }, { "text", "strings" },
                        { "and", "other" }, { "text", "values" } },
                new Object[] { "Column 1", "Column 2" });
        String[] columnNames= {null};
        DefaultTableModel model1 = new DefaultTableModel(null,columnNames);
        model1.setRowCount(0);


        JTable table = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(table);
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(300, 150);
        frame.setVisible(true);
        Thread.sleep(5000);
        table.setModel(model1);
    }


来源:https://stackoverflow.com/questions/23626951/jtable-row-count-vs-model-row-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!