Hello!

I would like to be able to change the sequence of rows in the JTable by clicking on arrows, which will be placed on the right side of the JTable.

Please, see an attached file to understand the idea.

Well, could someone please give me some advices on how to implement it?

Thanks!

Probably, I must use TableModel... Could someone please provide me some conceptual explanation of the steps to be done?

Well, I've found some ways to solve the problem. I must use "moveRow" method of DefaultTableModel. However, the new problem is that I have (and really need) AbstractTAbleModel... What should I do in this case?

I've solved the problem. The code for MOVE_UP button is shown below:

JButton butUp = new JButton(new ImageIcon("src/icons/ok.png"));
        butUp.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
                 int selRow = attrTable.getSelectedRow (  ) ;
 
                 int direction = MOVE_UP;
                 int destRow = selRow + direction;

                if  ( (destRow  >= 0) && (destRow < attrTable.getRowCount()) )   {
                   tableModel.moveRow ( selRow, selRow, destRow ) ;

                   attrTable.setColumnSelectionAllowed (false);
                   attrTable.setRowSelectionAllowed(true);
                   attrTable.setRowSelectionInterval (destRow, destRow) ;

                   attrTable.repaint (  ) ;
                }
            }
        });
private class QTableModel extends AbstractTableModel {
...
      public void moveRow(int start, int end, int to) {
         int shift = to - start;
         int first, last;
 	 if (shift < 0) {
             first = to;
             last = end;
         }
 	 else {
             first = start;
             last = to + end - start;
         }
         rotate(cache, first, last + 1, shift);
         fireTableRowsUpdated(first, last);
     }

      private void rotate(Vector v, int a, int b, int shift) {
        int size = b - a;
        int r = size - shift;
        int g = gcd(size, r);
	for(int i = 0; i < g; i++) {
          int to = i;
          Object tmp = v.elementAt(a + to);
	  for (int from = (to + r) % size; from != i; from = (to + r) % size) {
             v.setElementAt(v.elementAt(a + from), a + to);
             to = from;
          }
         v.setElementAt(tmp, a + to);
         }
      }

      private int gcd(int i, int j) {
        return (j == 0) ? i : gcd(j, i%j);
      }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.