

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 sort a JTable on a particular column in Java?
A JTable is a subclass of JComponent class for displaying complex data structures. A JTable component can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener interfaces. We can sort a JTable in a particular column by using the method setAutoCreateRowSorter() and set to true of JTable class.
Example
import java.awt.*; import javax.swing.*; public final class JTableSorterTest extends JFrame { private JTable table; private JScrollPane scrollPane; public JTableSorterTest() { setTitle("JTableHeaderHide Test"); String[] columnNames = {"Name", "Age", "City"}; Object[][] data = {{"Raja", "35", "Hyderabad"}, {"Adithya", "25", "Chennai"}, {"Vineet", "23", "Mumbai"}, {"Archana", "32", "Pune"}, {"Krishna", "30", "Kolkata"}}; table = new JTable(data, columnNames); scrollPane= new JScrollPane(table); table.setAutoCreateRowSorter(true); // sorting of the rows on a particular column add(scrollPane, BorderLayout.CENTER); setSize(375, 250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new JTableSorterTest(); } }
Output
- Related Questions & Answers
- How can we filter a JTable in Java?
- How we can perform sort on ObjectId column in MongoDB?
- How can we remove a selected row from a JTable in Java?
- How can we sort a JSONArray in Java?
- How can we sort a JSONObject in Java?
- How can we set the background/foreground color for individual column of a JTable in Java?
- How can we add/insert a JCheckBox inside a JTable cell in Java?
- How can we add/insert a JRadioButton to a JTable cell in Java?
- How can we add/insert a JButton to JTable cell in Java?
- How can we disable the cell editing inside a JTable in Java?
- How to set a value in a particular JTable cell with Java?
- Can we hide the table header from a JTable in Java?
- How can we implement the word wrap JTableHeader of a JTable in Java?
- How can we show/hide the table header of a JTable in Java?
- How can we prevent the re-ordering columns of a JTable in Java?
Advertisements