A JTable is a subclass of JComponent class and it can be used to create a table with information displayed in multiple rows and columns. When a value is selected from a JTable, a TableModelEvent is generated, which is handled by implementing a TableModelListener interface. By default, we can do the re-ordering of columns in a JTable. We can not allow the user to reorder columns by using table.getTableHeader().setReorderingAllowed() method and set the value as false.
Example
import java.awt.*;
import javax.swing.*;
public final class JTableColumnReorderingTest extends JFrame {
JTable table;
JScrollPane scrollPane;
public JTableColumnReorderingTest() {
setTitle("JTableColumnReordering Test");
String[] columnNames = {"Name", "Mobile Number", "Course"};
Object[][] data = {{"Raja", "123456789", "Java"}, {"Adithya", "456123789", ".Net"}, {"Vineet", "789456123", "Java Script"}, {"Archana", "987456321", "Python"}, {"Krishna", "321456987", "Scala"}, {"Jai", "456321789", "ServiceNow"}};
table = new JTable(data, columnNames);
scrollPane= new JScrollPane(table);
table.getTableHeader().setReorderingAllowed(false); // not allow re-ordering of columns
table.getTableHeader().setResizingAllowed(false);
add(scrollPane);
setSize(375, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JTableColumnReorderingTest();
}
}Output
