How to use sortable JTable?

R

Robert

Hi

I needed sortable table so I used TableSorter class from
Sun's JTable tutorial ("How to Use Tables").
Here is my code (comments are in Polish):

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


/**
* Tablica umieszczona w JScrollPane
* pozwalajaca na sortowanie wierszy wg wybranej kolumny
*/
class MASortableTable extends JScrollPane
{
JTable table;
MyTableModel myModel;
private TableSorter sorter;

/**
* Bezparametrowy konstruktor
*/
public MASortableTable()
{
this(new Vector());
} // MASortableTable()

/** Konstruktor
* @param l lista zawierajaca dane modelu tablicy MyTModel
*/
public MASortableTable(List l)
{
myModel = new MyTableModel(l);
TableSorter sorter = new TableSorter(myModel);
table = new JTable(sorter);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
sorter.addMouseListenerToHeaderInTable(table);
this.getViewport().add(table, null);
} // ManageAddressesSTable()

// /**
// * Ustawia tablice indeksy wierszy
// */
// public void setIndexes(int[] indexes)
// {
// sorter.indexes = indexes;
// }

public void addListSelectionListener(ListSelectionListener lslistener)
{
ListSelectionModel lsm = table.getSelectionModel();
lsm.addListSelectionListener(lslistener);
}

// public void addMouseListener(MouseListener ml)
// {
// table.addMouseListener(ml);
// }


//----------------------- klasa MyTableModel ----------------------------//


/**
* Model danych tabeli
*/
class MyTableModel extends AbstractTableModel {

final public String name = "Name";
final public String email = "Email Address";

/**
* Przechowuje dane modelu. Po zmianie na ArrayList
* wystapily bledy w dzialaniu.
*/
private Vector data = null;
private int NUM_COLUMNS = 2;
// protected static int START_NUM_ROWS = 5;
private int nextEmptyRow = 0;
private int numRows = 0;


//-------------------- Metody -----------------------------------//


public MyTableModel() {
data = new Vector();
}

public MyTableModel(List l) {
data = new Vector(l);
numRows = data.size();
nextEmptyRow = data.size();
}

public String getColumnName(int column) {
switch (column) {
case 0:
return name;
case 1:
return email;
}
return "";
}

public int getColumnCount() {
return NUM_COLUMNS;
}

public int getRowCount() {
// if (numRows < START_NUM_ROWS) {
// return START_NUM_ROWS;
// } else {
// return numRows;
// }
return numRows;
}

public Object getValueAt(int row, int column) {
try {
Entry e = (Entry)data.elementAt(row);
switch (column) {
case 0:
return e.getName();
case 1:
return e.getEmail();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return "";
}

/**
* Zwraca wszystkie wiersze modelu
* @return Lista zawierajaca wszystkie wiersze modelu
*/
public List getData()
{
return new ArrayList(data);
}

/**
* Dodaje wiersz do modelu
* @param entry dodawany obiekt typu Entry
*/
public void addRow(Entry entry)
{
int index;
++numRows;
index = nextEmptyRow;
data.addElement(entry);
++nextEmptyRow;

//zawiadom sluchaczy o zmianie danych
fireTableRowsInserted(index, index);
} // addRow()

/**
* Usuwa wiersz z modelu
* @param email wartosc kolumny Email usuwanego wiersza
* @throws Exception jezeli nie znaleziono wiersza do usuniecia
*/
public void deleteRow(String email) throws Exception
{
Entry e = null;
boolean found = false;
int index = 0;

while (!found && (index < nextEmptyRow)) {
e = (Entry)data.elementAt(index);
if (e.getEmail() == email) {
found = true;
}
else {
++index;
}
}

if (found) { //usun wiersz
data.removeElementAt(index);
--numRows;
--nextEmptyRow;
//zawiadom sluchaczy o zmianie danych
fireTableRowsDeleted(index, index);
}
else { //zglos wyjatek
throw new Exception("deleteRow(): the row wasn't found.");
}
} // deleteRow()

/**
* Edytuje wiersz w modelu
* @param email wartosc kolumny Email edytowanego wiersza
* @throws Exception jezeli nie znaleziono wiersza do edycji
*/
public void editRow(String email) throws Exception
{
Entry e = null;
boolean found = false;
int index = 0;

while (!found && (index < nextEmptyRow)) {
e = (Entry)data.elementAt(index);
if (e.getEmail() == email) {
found = true;
}
else {
++index;
}
}

if (found) { //edytuj wiersz
e = AddAddress.runAddAddress(e.getName(), e.getEmail(), false);
if(e != null) // zmieniono wiersz i nie jest on pusty
data.setElementAt(e,index);
//zawiadom sluchaczy o zmianie danych
fireTableRowsUpdated(index, index);
}
else { //zglos wyjatek
throw new Exception("editRow(): the row wasn't found.");
}
} // editRow()

} // class MyTModel

} // class MASortableTable
----------------------------------------------------------------------------
--------


I am using AbstractTableModel because I am dynamically deleting and adding
rows to the table.

I would like MASortableTable to extend only JTable,
eg.

class MASortableTable extends JTable
{
public MASortableTable(sorter)
{
super(sorter);
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
sorter.addMouseListenerToHeaderInTable(this);
} // MASortableTable()

....

} ),
but don't know how to do it.

I would be grateful for any help,
Robert
 
P

Paul Lutus

Robert said:
Hi

I needed sortable table so I used TableSorter class from
Sun's JTable tutorial ("How to Use Tables").

but don't know how to do it.

Neither do we. That's because you won't say what you want, only that you
cannot do it. You need to pose a specific problem, and ask for specific
help.

Posting copies of your earlier message unchanged will not do you any good.
You have to try supplying more information.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top