File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes Please Help in sorting JTable on multiple column. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Please Help in sorting JTable on multiple column." Watch "Please Help in sorting JTable on multiple column." New topic
Author

Please Help in sorting JTable on multiple column.

Sachin Dare
Greenhorn

Joined: May 04, 2004
Posts: 12
Hello World,
I have a class which sorts the table, on a column where user double clicks. This works fine. But now what I want instead of single column selection there will be some gui from which user can select multiple columns and table should get sorted on all those column.
Can anybody help me out how to do the sorting on multiple columns? I would appriciate if some one send me code.
Regards,
Sachin Dare.

Here is my existing code.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
import java.text.*;
public class Frame1 extends JFrame {
BorderLayout borderLayout1 = new BorderLayout();
JTable jTable1 ;
Object header[] = {"Jan","Feb","Mar","Apr"};
Object[][] data = {
{new Integer(14), new Integer(12), new Integer(134), new Integer(12) },
{new Integer(5), new Integer(3), new Integer(7), new Integer(2) },
{new Integer(8), new Integer(12), new Integer(123), new Integer(34)},
{new Integer(0), new Integer(0), new Integer(1), new Integer(2)}
};
public Frame1() {
super();
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
DefaultTableModel model = new DefaultTableModel(data,header);
SortFilterModel sortModel = new SortFilterModel(model);
jTable1 = new JTable(sortModel);
sortModel.addMouseListener(jTable1);
jTable1.setCellSelectionEnabled(true);
jTable1.setBackground(Color.pink);
jTable1.setAutoCreateColumnsFromModel(false);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(jTable1);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEE DED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED) ;
this.setTitle("Sort Table.");
getContentPane().setLayout(borderLayout1);
this.setSize(new Dimension(400, 300));
this.setBackground(Color.white);
getContentPane().add(scrollPane, BorderLayout.CENTER);
}
public static void main(String args[]) {
Frame1 myframe=new Frame1();
myframe.setSize(new Dimension(250,250));
myframe.setVisible(true);
}
}

class SortFilterModel extends AbstractTableModel {
private TableModel model;
private int sortColumn;
private Row[] rows;
public SortFilterModel(TableModel m) {
model = m;
int rowCount = model.getRowCount();
rows = new Row[rowCount];
for(int i=0;i<rows.length;i++) {
rows = new Row();
rows.index = i;
}
}
public void sort(int c) {
sortColumn = c;
Arrays.sort(rows);
fireTableDataChanged();
}
public void addMouseListener(final JTable table) {
table.getTableHeader().addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
int clickCount = me.getClickCount();
if(clickCount == 2) {
System.out.println("Clicked.......");
int tableColumn = table.columnAtPoint(me.getPoint());
int modelColumn = table.convertColumnIndexToModel(tableColumn);
sort(modelColumn);
}
}
});
}
public int getRowCount() {
return(model.getRowCount());
}
public int getColumnCount() {
return(model.getColumnCount());
}
public Object getValueAt(int row, int column) {
return(model.getValueAt(rows[row].index, column));
}
public void setValueAt(Object value, int row, int column) {
model.setValueAt(value, row, column);
}
public boolean isCellEditable(int r, int c) {
return false;
}
public String getColumnName(int c) {
return model.getColumnName(c);
}
public Class getColumnClass(int c) {
return model.getColumnClass(c);
}
private class Row implements Comparable {
public int index;
private int sortResult;
public int compareTo(Object other) {
try {
Row otherRow = (Row)other;
Object a = model.getValueAt(index, sortColumn);
Object b = model.getValueAt(otherRow.index, sortColumn);
if(a instanceof Comparable) {
sortResult = ((Comparable)a).compareTo(b);
} else {
sortResult = index - otherRow.index;
}
} catch(Exception e) {
e.printStackTrace();
}
return sortResult;
}
}
}
Sachin Dare
Greenhorn

Joined: May 04, 2004
Posts: 12
Ok, I have done it anyway,
Here is the code snippet.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
import java.text.*;



public class Frame1 extends JFrame
{

BorderLayout borderLayout1 = new BorderLayout();


Object header[] = {"Jan","Feb","Mar","Apr"};
Object[][] data = {
{new Integer(14), new Integer(12), new Integer(134), new Integer(12) },
{new Integer(5), new Integer(3), new Integer(7), new Integer(2) },
{new Integer(8), new Integer(12), new Integer(123), new Integer(34)},
{new Integer(0), new Integer(0), new Integer(1), new Integer(2)}
};

private JPopupMenu popupmenu = null;
private DefaultTableModel model = null;
private SortFilterModel sortModel = null;
private JTable jTable1 ;

public Frame1()
{
super();
try
{
jbInit();
}
catch (Exception e)
{
e.printStackTrace();
}
}

public Vector getColumnNameVector()
{
Vector columnVector = new Vector();
for(int i=0;i<header.length;i++)
{
columnVector.addElement(header[i]);
}
return columnVector;
}
private void jbInit() throws Exception
{
model = new DefaultTableModel(data,header);
sortModel = new SortFilterModel(model);
jTable1 = new JTable(sortModel);
sortModel.addMouseListener(jTable1);

jTable1.setCellSelectionEnabled(true);
jTable1.setBackground(Color.pink);
jTable1.setAutoCreateColumnsFromModel(false);

jTable1.add(getJPopupMenu());
jTable1.addMouseListener(new MouseListenerHandler());

JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(jTable1);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);


this.setTitle("Sort Table.");

getContentPane().setLayout(borderLayout1);
this.setSize(new Dimension(400, 300));
this.setBackground(Color.white);
getContentPane().add(scrollPane, BorderLayout.CENTER);
}



public JPopupMenu getJPopupMenu()
{
if(popupmenu == null)
{
popupmenu = new JPopupMenu();
JMenuItem menuitem = new JMenuItem("Sort");
menuitem.addActionListener(new ActionListenerHandler());
popupmenu.add(menuitem);
}
return popupmenu;
}
class MouseListenerHandler extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
if(e.getButton() == MouseEvent.BUTTON3)
{
System.out.println(e.getButton());
popupmenu.show(e.getComponent(),e.getX(), e.getY());
}
}
}

class ActionListenerHandler implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("Button Clicked....");
SortSelection obj = new SortSelection(null,"Sort",true);

ArrayList selectionList = obj.getSelectionList();

if(selectionList != null)
{
ArrayList selectedColumnList = (ArrayList)selectionList.get(0);
ArrayList radioSelectionList = (ArrayList)selectionList.get(1);

for(int i=0;i<selectedColumnList.size(); i++)
{
System.out.println(selectedColumnList.get(i));
System.out.println(radioSelectionList.get(i));

int columnNumber = Integer.parseInt((String)selectedColumnList.get(i));
boolean ascendingFlag = ((Boolean)radioSelectionList.get(i)).booleanValue();
sortModel.sort(columnNumber, ascendingFlag);
}
}
}
}

public static void main(String args[])
{
Frame1 myframe=new Frame1();
myframe.setSize(new Dimension(250,250));
myframe.setVisible(true);
}


}


class SortFilterModel extends AbstractTableModel
{
private TableModel model;
private int sortColumn;
private Row[] rows;


public SortFilterModel(TableModel m)
{
model = m;
int rowCount = model.getRowCount();

rows = new Row[rowCount];
for(int i=0;i<rows.length;i++)
{
rows[i] = new Row();
rows[i].index = i;
}
}

public void sort(int c, boolean ascendingFlag)
{
sortColumn = c;
for(int i=0;i<rows.length;i++)
{
rows[i].setAscendingFlag(ascendingFlag);
}
Arrays.sort(rows);
fireTableDataChanged();
}


public void addMouseListener(final JTable table)
{
table.getTableHeader().addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
int clickCount = me.getClickCount();
if(clickCount == 2)
{
System.out.println("Double Clicked.......");
int tableColumn = table.columnAtPoint(me.getPoint());
int modelColumn = table.convertColumnIndexToModel(tableColumn);
sort(modelColumn, true);
}
}
});
}


public int getRowCount()
{
return(model.getRowCount());
}

public int getColumnCount()
{
return(model.getColumnCount());
}

public Object getValueAt(int row, int column)
{
return(model.getValueAt(rows[row].index, column));
}

public void setValueAt(Object value, int row, int column)
{
model.setValueAt(value, row, column);
}

public boolean isCellEditable(int r, int c)
{
return false;
}
public String getColumnName(int c)
{
return model.getColumnName(c);
}
public Class getColumnClass(int c)
{
return model.getColumnClass(c);
}



private class Row implements Comparable
{
public int index;
private int sortResult;
private boolean ascending = true;

public void setAscendingFlag(boolean ascendingFlag)
{
ascending = ascendingFlag;
}
public int compareTo(Object other)
{
try
{
Row otherRow = (Row)other;
Object a = model.getValueAt(index, sortColumn);
Object b = model.getValueAt(otherRow.index, sortColumn);
if(a instanceof Comparable)
{
if(ascending == true)
{
sortResult = ((Comparable)a).compareTo(b);
}
else
{
sortResult = ((Comparable)b).compareTo(a);
}
}
else
{
if(ascending == true)
{
sortResult = index - otherRow.index;
}
else
{
sortResult = otherRow.index - index;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return sortResult;
}
}

}


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.*;


public class SortSelection extends JDialog
{
Container cont = getContentPane();

private JComboBox firstColumnCombo = null;
private JComboBox secondColumnCombo = null;
private JComboBox thirdColumnCombo = null;

private JPanel firstSelectionPanel = null;
private JPanel secondSelectionPanel = null;
private JPanel thirdSelectionPanel = null;
private JPanel buttonPanel = null;

private JButton okButton = null;
private JButton cancelButton = null;
private ActionEventHandler handler = new ActionEventHandler();

private JRadioButton firstAscendingRadioButton = null;
private JRadioButton secondAscendingRadioButton = null;
private JRadioButton thirdAscendingRadioButton = null;

private JRadioButton firstDescendingRadioButton = null;
private JRadioButton secondDescendingRadioButton = null;
private JRadioButton thirdDescendingRadioButton = null;


private ArrayList selectionList = null;

public SortSelection(Frame owner, String title, boolean modal)
{
super(owner, title, modal);
cont.setLayout(null);
setSize(290,304);
addComponents();
setVisible(true);
}

public void addComponents()
{
cont.add(getFirstSelectionPanel());
cont.add(getSecondSelectionPanel());
cont.add(getThirdSelectionPanel());
cont.add(getButtonPanel());
}

public JComboBox getFirstColumnCombo()
{
if(firstColumnCombo == null)
{
firstColumnCombo = new JComboBox(getColumnNameVector());
firstColumnCombo.setBounds(10,25,130,25);
}
return firstColumnCombo;
}

public JComboBox getSecondColumnCombo()
{
if(secondColumnCombo == null)
{
secondColumnCombo = new JComboBox(getColumnNameVector());
secondColumnCombo.setBounds(10,25,130,25);
}
return secondColumnCombo;
}

public JComboBox getThirdColumnCombo()
{
if(thirdColumnCombo == null)
{
thirdColumnCombo = new JComboBox(getColumnNameVector());
thirdColumnCombo.setBounds(10,25,130,25);
}
return thirdColumnCombo;
}

public JPanel getFirstSelectionPanel()
{
if(firstSelectionPanel == null)
{
firstSelectionPanel = new JPanel();
firstSelectionPanel.setLayout(null);
firstSelectionPanel.setBounds(2,0,278,72);
firstSelectionPanel.setBorder(new TitledBorder("Sort by "));
firstSelectionPanel.add(getFirstColumnCombo());
firstSelectionPanel.add(getFirstAscendingRadioButton());
firstSelectionPanel.add(getFirstDescendingRadioButton());

ButtonGroup groupFirst = new ButtonGroup();
groupFirst.add(getFirstAscendingRadioButton());
groupFirst.add(getFirstDescendingRadioButton());
}
return firstSelectionPanel;
}

public JPanel getSecondSelectionPanel()
{
if(secondSelectionPanel == null)
{
secondSelectionPanel = new JPanel();
secondSelectionPanel.setLayout(null);
secondSelectionPanel.setBounds(2,74,278,72);
secondSelectionPanel.setBorder(new TitledBorder("Then by "));
secondSelectionPanel.add(getSecondColumnCombo());
secondSelectionPanel.add(getSecondAscendingRadioButton());
secondSelectionPanel.add(getSecondDescendingRadioButton());

ButtonGroup groupSecond = new ButtonGroup();
groupSecond.add(getSecondAscendingRadioButton());
groupSecond.add(getSecondDescendingRadioButton());

}
return secondSelectionPanel;
}

public JPanel getThirdSelectionPanel()
{
if(thirdSelectionPanel == null)
{
thirdSelectionPanel = new JPanel();
thirdSelectionPanel.setLayout(null);
thirdSelectionPanel.setBounds(2,148,280,72);
thirdSelectionPanel.setBorder(new TitledBorder("Then by "));
thirdSelectionPanel.add(getThirdColumnCombo());
thirdSelectionPanel.add(getThirdAscendingRadioButton());
thirdSelectionPanel.add(getThirdDescendingRadioButton());

ButtonGroup groupThird = new ButtonGroup();
groupThird.add(getThirdAscendingRadioButton());
groupThird.add(getThirdDescendingRadioButton());
}
return thirdSelectionPanel;
}

public JPanel getButtonPanel()
{
if(buttonPanel == null)
{
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setBounds(2,222,280,72);
buttonPanel.add(getOkButton());
buttonPanel.add(getCancelButton());
}
return buttonPanel;
}

public JButton getOkButton()
{
if(okButton == null)
{
okButton = new JButton("Ok");
okButton.setBounds(60,8,80,25);
okButton.addActionListener(handler);
}
return okButton;
}

public JButton getCancelButton()
{
if(cancelButton == null)
{
cancelButton = new JButton("Cancel");
cancelButton.setBounds(141,8,80,25);
cancelButton.addActionListener(handler);
}
return cancelButton;
}


// Code for getting RadioButtons.


public JRadioButton getFirstAscendingRadioButton()
{
if(firstAscendingRadioButton == null)
{
firstAscendingRadioButton = new JRadioButton("Ascending");
firstAscendingRadioButton.setSelected(true);
firstAscendingRadioButton.setBounds(155,17,100,25);
}
return firstAscendingRadioButton;
}

public JRadioButton getSecondAscendingRadioButton()
{
if(secondAscendingRadioButton == null)
{
secondAscendingRadioButton = new JRadioButton("Ascending");
secondAscendingRadioButton.setSelected(true);
secondAscendingRadioButton.setBounds(155,17,100,25);
}
return secondAscendingRadioButton;
}

public JRadioButton getThirdAscendingRadioButton()
{
if(thirdAscendingRadioButton == null)
{
thirdAscendingRadioButton = new JRadioButton("Ascending");
thirdAscendingRadioButton.setSelected(true);
thirdAscendingRadioButton.setBounds(155,17,100,25);
}
return thirdAscendingRadioButton;
}

public JRadioButton getFirstDescendingRadioButton()
{
if(firstDescendingRadioButton == null)
{
firstDescendingRadioButton = new JRadioButton("Descending");
firstDescendingRadioButton.setBounds(155,37,100,25);
}
return firstDescendingRadioButton;
}

public JRadioButton getSecondDescendingRadioButton()
{
if(secondDescendingRadioButton == null)
{
secondDescendingRadioButton = new JRadioButton("Descending");
secondDescendingRadioButton.setBounds(155,37,100,25);
}
return secondDescendingRadioButton;
}

public JRadioButton getThirdDescendingRadioButton()
{
if(thirdDescendingRadioButton == null)
{
thirdDescendingRadioButton = new JRadioButton("Descending");
thirdDescendingRadioButton.setBounds(155,37,100,25);
}
return thirdDescendingRadioButton;
}


public Vector getColumnNameVector()
{
//Frame1 obj = new Frame1();
//return (obj.getColumnNameVector());

Vector columnVector = new Vector();
//columnVector.addElement("SELECT");
columnVector.addElement("Jan");
columnVector.addElement("Feb");
columnVector.addElement("Mar");
columnVector.addElement("Apr");
return columnVector;
}

public ArrayList getSelectionList()
{
if(selectionList != null)
{
return selectionList;
}
return null;
}

class ActionEventHandler implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{

if(ae.getSource() == getOkButton())
{
if(selectionList == null)
{
selectionList = new ArrayList();

ArrayList comboSelectionList = new ArrayList();
ArrayList radioSelectionList = new ArrayList();




if(!(((String)getFirstColumnCombo().getSelectedItem()).equalsIgnoreCase("SELECT")))
{
comboSelectionList.add("" + getFirstColumnCombo().getSelectedIndex());
if(getFirstAscendingRadioButton().isSelected() == true)
{
radioSelectionList.add(new Boolean(true));
}
else
{
radioSelectionList.add(new Boolean(false));
}
}

if(!(((String)getSecondColumnCombo().getSelectedItem()).equalsIgnoreCase("SELECT")))
{
comboSelectionList.add("" + getSecondColumnCombo().getSelectedIndex());
if(getSecondAscendingRadioButton().isSelected() == true)
{
radioSelectionList.add(new Boolean(true));
}
else
{
radioSelectionList.add(new Boolean(false));
}
}

if(!(((String)getThirdColumnCombo().getSelectedItem()).equalsIgnoreCase("SELECT")))
{
comboSelectionList.add("" + getThirdColumnCombo().getSelectedIndex());
if(getThirdAscendingRadioButton().isSelected() == true)
{
radioSelectionList.add(new Boolean(true));
}
else
{
radioSelectionList.add(new Boolean(false));
}
}
selectionList.add(comboSelectionList);
selectionList.add(radioSelectionList);
selectionList.trimToSize();
dispose();
}
}
if(ae.getSource() == getCancelButton())
{
SortSelection.this.dispose();
}
}
}

}
 
Don't get me started about those stupid light bulbs.
 
subject: Please Help in sorting JTable on multiple column.