![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e911. Moving a Row in a JTable ComponentTo move a row of data to aJTable component, you need to move it
in its table model. A simple implementation of a table model that
supports the moving of row data is DefaultTableModel .
When moving one or more rows using
The destination is also a position. Positions are locations between
rows. For example, if there are 2 rows in a table, there are 3
possible positions - - 0, 1,and 2. The important thing to remember about
the destination position is that it specifies the position in the row
data after the rows to be moved are taken out of the row
data. For example, if you want to move the first row to the end of the
table, the destination position is not The way in which the parameters are interpreted is somewhat
awkward. The more conventional method is to either make the end index
exclusive (like DefaultTableModel model = new DefaultTableModel(); JTable table = new JTable(model); // Create some data model.addColumn("Col1"); model.addRow(new Object[]{"r1"}); model.addRow(new Object[]{"r2"}); model.addRow(new Object[]{"r3"}); // Move the first row to the end of the table model.moveRow(0, 0, model.getRowCount()-1); betterMoveRow(model, 0, 1, model.getRowCount()); // Move the last row to the beginning of the table model.moveRow(model.getRowCount()-1, model.getRowCount()-1, 0); betterMoveRow(model, model.getRowCount()-1, model.getRowCount(), 0); // Move the first two rows to the end of the table model.moveRow(0, 1, model.getRowCount()-2); betterMoveRow(model, 0, 2, model.getRowCount()); // Move the last two rows to the start of the table model.moveRow(model.getRowCount()-2, model.getRowCount()-1, 0); betterMoveRow(model, model.getRowCount()-2, model.getRowCount(), 0); // A better version of moveRow(). // Moves all rows contained between the positions start and end // to the position specified by dest. public static void betterMoveRow(DefaultTableModel model, int start, int end, int dest) { int count = end - start; if (count <= 0) { return; } if (dest > start) { dest = Math.max(start, dest-count); } end--; model.moveRow(start, end, dest); }
e908. Appending a Row to a JTable Component e909. Inserting a Row in a JTable Component e910. Removing a Row from a JTable Component e912. Copying a Row or Column in a JTable Component e913. Setting the Height of a Row in a JTable Component e914. Shading Rows and Columns in a JTable Component
© 2002 Addison-Wesley. |