Java examples for Swing:JTable Row
Move rows in a JTable using a JSpinner
//package com.java2s; import java.util.Map; import javax.swing.JSpinner; import javax.swing.JTable; import javax.swing.SpinnerNumberModel; import javax.swing.table.DefaultTableModel; public class Main { /**/*from w w w.j av a 2s . c o m*/ * Save previous index of JSpinner for a certain JTable */ private static Map<JTable, Integer> spinnerMovesTableMap; /** * Move rows in a JTable using a JSpinner * * @param selectedRow * @param table * @param spinner */ public static void spinnerMovesTableRow(JTable table, JSpinner spinner, Integer selectedRow) { DefaultTableModel tableModel = null; SpinnerNumberModel spinnerModel = null; int value = -1; Integer previousValue = null; int row = -1; int newRow = -1; spinnerModel = (SpinnerNumberModel) spinner.getModel(); value = Integer.valueOf("" + spinnerModel.getValue()); previousValue = spinnerMovesTableMap.get(table); if (previousValue == null) { previousValue = 0; } tableModel = (DefaultTableModel) table.getModel(); if (selectedRow == null) { row = table.getSelectedRow(); } else { row = selectedRow; } newRow = row; // Move up if (previousValue < value) { // Calculate new row newRow = row - 1; if (newRow == -1) { newRow = table.getRowCount() - 1; } } // Move down else if (previousValue > value) { // Calculate new row newRow = row + 1; if (newRow == table.getRowCount()) { newRow = 0; } } // Move row in table tableModel.moveRow(row, row, newRow); // Select/highlight new row table.changeSelection(newRow, 0, false, false); // Save actual value as previous value spinnerMovesTableMap.put(table, new Integer(value)); } /** * * @param table * @param spinner */ public static void spinnerMovesTableRow(JTable table, JSpinner spinner) { spinnerMovesTableRow(table, spinner, null); } }