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").
Here is my code (comments are in Polish):

You need to stop creating new threads on this same topic.

Here is the meat of yor post:
I am using AbstractTableModel because I am dynamically deleting and adding
rows to the table.
I would like MASortableTable to extend only JTable,
but don't know how to do it.

Post at most twenty lines of compilable code that shows the problem, and be
sure to say specifically what you want but cannot have. Include any error
messages.

Code like this:

*********************************************************

import javax.swing.*;

public class MASortableTable extends JTable {

public static void main(String[] args) throws Exception
{
Class cls = MASortableTable.class;
do {
System.out.println("Class name: " + cls.getName());
cls = cls.getSuperclass();
}
while(cls != null);
}
}

*********************************************************

Results:

Class name: MASortableTable
Class name: javax.swing.JTable
Class name: javax.swing.JComponent
Class name: java.awt.Container
Class name: java.awt.Component
Class name: java.lang.Object

Where exactly is the problem that makes you post this same inquiry over and
over again?
 
S

soft-eng

Robert said:
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.

Well, you have done it. Just remove any references
to "table." (replace with empty string), and fix
any syntax errors you might get because of accessing
the frame. Then test in another frame.
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top