Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort JTable in shortest way?

I was searching for Sorting in JTable and I referred many articles, but couldn't get the easiest way to sort the table. I also know that TableRowSorter could be somehow helpful but don't know how. Being new to JTable, I am creating a new question here.

My table structure is something like this

| People  | Place |   Organisation    | Event    | Mentions |
_____________________________________________________________
| Ramanuj | India | Tata Consultancy  | Party'14 |  500000  |
| Prankster | USA | Microsoft Pvt Ltd | Party'14 |  900000  |

What I want here is to sort my table Descending based on 4th column ("Mentions"). If counts (Mentions) are same, it should sort Ascending by 1st column ("People")

CSVReader reader = new CSVReader(new FileReader(file)); 

List<String[]> myEntries = reader.readAll();
String[][] rowData = myEntries.toArray(new String[0][]);

String[] columnNames = { "People", "Place", "Organisation", "Event", "Mentions" };

DefaultTableModel tableModel = new DefaultTableModel(rowData, columnNames);
like image 574
Pratik Avatar asked Mar 03 '15 03:03

Pratik


People also ask

How do I sort a row in JTable?

We can sort a JTable in a particular column by using the method setAutoCreateRowSorter() and set to true of JTable class.

What is JTable and how it is created?

The JTable class is a part of Java Swing Package and is generally used to display or edit two-dimensional data that is having both rows and columns. It is similar to a spreadsheet. This arranges data in a tabular form. Constructors in JTable: JTable(): A table is created with empty cells.

What is JTable TableModel?

The TableModel interface specifies the methods the JTable will use to interrogate a tabular data model. The JTable can be set up to display any data model which implements the TableModel interface with a couple of lines of code: TableModel myData = new MyTableModel(); JTable table = new JTable(myData);


1 Answers

As per How to Use Tables: Sorting and Filtering

JTable table = new JTable(tableModel);
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel());
table.setRowSorter(sorter);

List<RowSorter.SortKey> sortKeys = new ArrayList<>(25);
sortKeys.add(new RowSorter.SortKey(4, SortOrder.ASCENDING));
sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);

Updated

Are you sure it will sort?

...Yes

Table

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                DefaultTableModel model = new DefaultTableModel(new String[]{"People", "Place", "Organisation", "Event", "Mentions"}, 0);
                model.addRow(new Object[]{"Prankster", "USA", "Microsoft Pvt Ltd", "Party'14", 900000});
                model.addRow(new Object[]{"Ramanuj", "India", "Tata Consultancy", "Party'14", 500000});
                model.addRow(new Object[]{"Banana", "India", "Tata Consultancy", "Party'14", 500000});

                JTable table = new JTable(model);
                TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(table.getModel());
                table.setRowSorter(sorter);

                List<RowSorter.SortKey> sortKeys = new ArrayList<>(25);
                sortKeys.add(new RowSorter.SortKey(4, SortOrder.ASCENDING));
                sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
                sorter.setSortKeys(sortKeys);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new JScrollPane(table));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

Updated

You can extract the data from the view directly...

 for (int row = 0; row < table.getRowCount(); row++) {
     String people = table.getValueAt(row, 0).toString();
     String place = table.getValueAt(row, 1).toString();
     String organisation = table.getValueAt(row, 2).toString();
     String event = table.getValueAt(row, 3).toString();
     int mentions = (int)table.getValueAt(row, 4);
     //...
 }

This will give you the data in the "view" (or sorted) order...

like image 188
MadProgrammer Avatar answered Sep 20 '22 07:09

MadProgrammer