![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we prevent the re-ordering columns of a JTable in Java?
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
Advertisements