【问题标题】:Moving a row in jTable在 jTable 中移动一行
【发布时间】:2010-12-03 19:05:27
【问题描述】:

如何在jTable 中移动一行,以便 row1row2 的位置,而 row2第1行的位置?

【问题讨论】:

    标签: java swing jtable tablemodel


    【解决方案1】:

    这是我刚刚使用这个问题的答案开发的代码。 使用这些功能,您可以一次选择多行并在JTable 中向下或向上移动它们。我已将这些函数附加到 JButton,但我将它们清理掉以使其更具可读性。

    这两种方法的最后一行代码 (setRowSelectionInterval()) 用于跟随正在移动的行上的选择,因为 moveRow() 不会移动选择,而是移动行的内容。

    public void moveUpwards()
    {
        moveRowBy(-1);
    }
    
    public void moveDownwards()
    {
        moveRowBy(1);
    }
    
    private void moveRowBy(int by)
    {
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        int[] rows = table.getSelectedRows();
        int destination = rows[0] + by;
        int rowCount = model.getRowCount();
    
        if (destination < 0 || destination >= rowCount)
        {
            return;
        }
    
        model.moveRow(rows[0], rows[rows.length - 1], destination);
        table.setRowSelectionInterval(rows[0] + by, rows[rows.length - 1] + by);
    }
    

    【讨论】:

      【解决方案2】:

      使用DefaultTableModelmoveRow(...) 方法。

      或者,如果您不使用 DefaultTableModel,则在您的自定义模型中实现一个类似的方法。

      【讨论】:

      • 我没有注意到有链接。这很有帮助。谢谢。
      • 示例链接已被删除。您现在需要阅读 API 以了解正确的语法。
      【解决方案3】:
      TableModel model = jTable.getModel();
      for(int col=0; col<model.getColumnCount(); col++) {
        Object o1 = model.getValueAt(row1, col);
        Object o2 = model.getValueAt(row2, col);
        model.setValueAt(o1, row2, col);
        model.setValueAt(o2, row1, col);
      }
      

      【讨论】:

        猜你喜欢
        • 2013-01-09
        • 1970-01-01
        • 2012-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多