Java Tutorial/Swing/JTable Model — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 15:32, 31 мая 2010
Содержание
- 1 Add columns to a table through DefaultTableModel
- 2 Add logic to get value method
- 3 Add rows to a Table
- 4 Append a row to a table through DefaultTableModel at specified row
- 5 Appending a Row to a JTable Component
- 6 Bean Property Table Model
- 7 Copy (clone) the data from the second row
- 8 Copy data from a table to a list
- 9 Create DefaultTableModel
- 10 Creates tables that allow rows and columns to be added or deleted
- 11 Creating simple JTable using AbstractTableModel
- 12 Disabling User Edits in a JTable with DefaultTableModel
- 13 Extending AbstractTableModel
- 14 Get all the table data from DefaultTableModel
- 15 Insert a row to a table through DefaultTableModel
- 16 Insert a row to a table through DefaultTableModel at specified row
- 17 Listening to JTable Events with a TableColumnModelListener
- 18 Map TableModel
- 19 Move the first row to the end of the table
- 20 Move the first two rows to the end of the table
- 21 Move the last row to the beginning of the table
- 22 Move the last two rows to the start of the table
- 23 Overwrite the date from the first row with DefaultTableModel
- 24 Remove the first row from a table with DefaultTableModel
- 25 Remove the last row from a table with DefaultTableModel
- 26 Sample Sorting Table Model
- 27 Set table value
- 28 Sharing a Table Model Between JTable Components
- 29 Sparsely Populated Table Model
- 30 Subclass AbstractTableModel to reuse an existing data structure: Treat an array as an AbstractTableModel
- 31 The Calendar program.
Add columns to a table through DefaultTableModel
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Col1");
model.addColumn("Col2");
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Add logic to get value method
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class GetValueAtLogic extends JFrame {
public GetValueAtLogic() {
JTable table = new JTable(new CoordinateTableModel());
getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
pack();
}
public static void main(String arg[]) {
GetValueAtLogic ex1 = new GetValueAtLogic();
ex1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ex1.setVisible(true);
}
}
class CoordinateTableModel extends AbstractTableModel {
private int[] x = { 2, 3, 5, 7, 11, 13, 17, 19 }; // x is prime < 20
public int getColumnCount() {
return 2;
}
public int getRowCount() {
return x.length;
}
public Object getValueAt(int r, int c) {
return (c == 0) ? new Integer(x[r]) : new Integer(2 * x[r] + 1);
}
public String getColumnName(int c) {
return (c == 0) ? "x" : "2x+1";
}
}
Add rows to a Table
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ruponentAdapter;
import java.awt.event.ruponentEvent;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
public class RowAdder extends JFrame {
final SimpleModel tableData = new SimpleModel();
JTable table = new JTable(tableData);
public static void main(String[] args) {
RowAdder ra = new RowAdder();
ra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ra.setSize(400, 300);
ra.setVisible(true);
}
public RowAdder() {
final JTextField textField = new JTextField();
setLayout(new BorderLayout());
add(new JScrollPane(table), BorderLayout.CENTER);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
tableData.addText(textField.getText());
textField.setText("");
}
});
add(textField, BorderLayout.SOUTH);
}
}
class SimpleModel extends AbstractTableModel {
Vector textData = new Vector();
public void addText(String text) {
textData.addElement(text);
fireTableDataChanged();
}
public int getRowCount() {
return textData.size();
}
public int getColumnCount() {
return 3;
}
public Object getValueAt(int row, int column) {
return textData.elementAt(row);
}
}
Append a row to a table through DefaultTableModel at specified row
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Col1");
model.addColumn("Col2");
// Create the first row
model.insertRow(0, new Object[] { "r1" });
// Append a row
model.insertRow(model.getRowCount(), new Object[] { "r5" });
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Appending a Row to a JTable Component
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Col1");
model.addColumn("Col2");
model.addRow(new Object[] { "v1", "v2" });
model.addRow(new Object[] { "v1" });
model.addRow(new Object[] { "v1", "v2", "v3" });
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Bean Property Table Model
/*
* Copyright (C) 2001-2003 Colin Bell
* colbell@users.sourceforge.net
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.ruparator;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
public class BeanPropertyTableModel extends DefaultTableModel
{
private static final long serialVersionUID = 1L;
private Object _bean;
private String _nameColumnName = "Namecolumn";
private String _valueColumnName = "Valuecolumn";
public BeanPropertyTableModel()
{
super();
}
public void setBean(Object bean) throws RuntimeException
{
_bean = bean;
refresh();
}
public void refresh() throws RuntimeException
{
final Vector<Object> columnNames = new Vector<Object>();
columnNames.add(_nameColumnName);
columnNames.add(_valueColumnName);
final Vector<Object> columnData = new Vector<Object>();
if (_bean != null)
{
try
{
BeanInfo info = Introspector.getBeanInfo(_bean.getClass(), Introspector.USE_ALL_BEANINFO);
processBeanInfo(info, columnData);
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
}
// Sort the rows by the property name.
Collections.sort(columnData, new DataSorter());
setDataVector(columnData, columnNames);
}
private void processBeanInfo(BeanInfo info, Vector<Object> columnData)
throws InvocationTargetException, IllegalAccessException
{
BeanInfo[] extra = info.getAdditionalBeanInfo();
if (extra != null)
{
for (int i = 0; i < extra.length; ++i)
{
processBeanInfo(extra[i], columnData);
}
}
PropertyDescriptor[] propDesc = info.getPropertyDescriptors();
for (int i = 0; i < propDesc.length; ++i)
{
final String propName = propDesc[i].getName();
final Method getter = propDesc[i].getReadMethod();
if (propName != null && getter != null)
{
Vector<Object> line = generateLine(propName, _bean, getter);
if (line != null)
{
columnData.add(line);
}
}
}
}
/**
* Generate a line for the passed property.
*
* @param propName Name of the property.
* @param bean Bean containg the property.
* @param getter The "getter" function to retrieve the
* properties value.
*
* @return A <CODE>Vector</CODE> containing the cells for the line in
* the table. Element zero the first cell etc. Return
* <CODE>null</CODE> if this property is <B>not</B> to be added
* to the table.
*/
protected Vector<Object> generateLine(String propName, Object bean, Method getter)
throws InvocationTargetException, IllegalAccessException
{
final Vector<Object> line = new Vector<Object>();
line.add(propName);
line.add(executeGetter(bean, getter));
return line;
}
protected Object executeGetter(Object bean, Method getter)
throws InvocationTargetException, IllegalAccessException
{
return getter.invoke(bean, (Object[])null);
}
public void setNameColumnName(String value)
{
_nameColumnName = value;
}
public void setValueColumnName(String value)
{
_valueColumnName = value;
}
/**
* This comparator is compatible with the strange use of lists in this
* class. This classes lists are Vectors with Strings as the first element
* and any object as the other objects.
*/
private static final class DataSorter implements Comparator<Object>
{
public int compare(Object o1, Object o2)
{
Vector<Object> v1 = (Vector<Object>)o1;
Vector<Object> v2 = (Vector<Object>)o2;
String lhs = (String)v1.get(0);
String rhs = (String)v2.get(0);
return lhs.rupareToIgnoreCase(rhs);
}
}
}
Copy (clone) the data from the second row
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Col1");
model.addRow(new Object[] { "r1" });
model.addRow(new Object[] { "r2" });
model.addRow(new Object[] { "r3" });
// Get all the table data
Vector data = model.getDataVector();
// Copy the second row
Vector row = (Vector) data.elementAt(1);
row = (Vector) row.clone();
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Copy data from a table to a list
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Col1");
model.addRow(new Object[] { "r1" });
model.addRow(new Object[] { "r2" });
model.addRow(new Object[] { "r3" });
Vector data = model.getDataVector();
Vector row = (Vector) data.elementAt(1);
// Copy the first column
int mColIndex = 0;
List colData = new ArrayList(table.getRowCount());
for (int i = 0; i < table.getRowCount(); i++) {
row = (Vector) data.elementAt(i);
colData.add(row.get(mColIndex));
}
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Create DefaultTableModel
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main extends JFrame {
DefaultTableModel model = new DefaultTableModel(new Object[][] {
{ "some", "text" }, { "any", "text" }, { "even", "more" },
{ "text", "strings" }, { "and", "other" }, { "text", "values" } },
new Object[] { "Column 1", "Column 2" });
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table = new JTable(model);
getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
pack();
}
public static void main(String arg[]) {
new Main().setVisible(true);
}
}
Creates tables that allow rows and columns to be added or deleted
import java.util.Arrays;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) {
int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Creating simple JTable using AbstractTableModel
import java.awt.Dimension;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class Main extends JFrame {
private JTable m_simpleTable;
private SimpleTableModel m_simpleTableModel;
public Main() {
Vector dummyMacData = new Vector(10, 10);
dummyMacData.addElement(new Data(new Integer(100), "A", "1","C", "E"));
dummyMacData.addElement(new Data(new Integer(105), "R", "2","S", "E"));
m_simpleTableModel = new SimpleTableModel(dummyMacData);
m_simpleTable = new JTable(m_simpleTableModel);
JScrollPane scrollPane = new JScrollPane(m_simpleTable);
getContentPane().add(scrollPane);
}
public static void main(String[] arg) {
Main m = new Main();
m.setVisible(true);
m.setSize(new Dimension(600, 300));
m.validate();
}
class SimpleTableModel extends AbstractTableModel {
public String[] m_colNames = { "A", "B", "C","D", "E" };
public Class[] m_colTypes = { Integer.class, String.class, String.class, String.class,
String.class };
Vector m_macDataVector;
public SimpleTableModel(Vector macDataVector) {
super();
m_macDataVector = macDataVector;
}
public int getColumnCount() {
return m_colNames.length;
}
public int getRowCount() {
return m_macDataVector.size();
}
public void setValueAt(Object value, int row, int col) {
Data macData = (Data) (m_macDataVector.elementAt(row));
switch (col) {
case 0:
macData.setA((Integer) value);
break;
case 1:
macData.setB((String) value);
break;
case 2:
macData.setC((String) value);
break;
case 3:
macData.setD((String) value);
break;
case 4:
macData.setE((String) value);
break;
}
}
public String getColumnName(int col) {
return m_colNames[col];
}
public Class getColumnClass(int col) {
return m_colTypes[col];
}
public Object getValueAt(int row, int col) {
Data macData = (Data) (m_macDataVector.elementAt(row));
switch (col) {
case 0:
return macData.getA();
case 1:
return macData.getB();
case 2:
return macData.getC();
case 3:
return macData.getD();
case 4:
return macData.getE();
}
return new String();
}
}
}
class Data {
private Integer a;
private String b;
private String c;
private String d;
private String e;
public Data() {
}
public Data(Integer aa, String bb, String cc, String dd, String ee) {
a = aa;
b = bb;
c = cc;
d = dd;
e = ee;
}
public Integer getA() {
return a;
}
public String getB() {
return b;
}
public String getC() {
return c;
}
public String getD() {
return d;
}
public String getE() {
return e;
}
public void setA(Integer aa) {
a = aa;
}
public void setB(String macName) {
b = macName;
}
public void setC(String cc) {
c = cc;
}
public void setD(String dd) {
d = dd;
}
public void setE(String ee) {
e = ee;
}
}
Disabling User Edits in a JTable with DefaultTableModel
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class Main {
public static void main(String[] argv) throws Exception {
TableModel model = new DefaultTableModel() {
public boolean isCellEditable(int rowIndex, int mColIndex) {
return false;
}
};
JTable table2 = new JTable(model);
}
}
Extending AbstractTableModel
import java.awt.BorderLayout;
import java.awt.Container;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
class TableValues extends AbstractTableModel {
public final static int FIRST_NAME = 0;
public final static int LAST_NAME = 1;
public final static int DATE_OF_BIRTH = 2;
public final static int ACCOUNT_BALANCE = 3;
public final static int GENDER = 4;
public final static boolean GENDER_MALE = true;
public final static boolean GENDER_FEMALE = false;
public Object[][] values = {
{ "C", "A", new GregorianCalendar(1962, Calendar.FEBRUARY, 20).getTime(),
new Float(15.67), new Boolean(GENDER_MALE) },
{ "J", "A", new GregorianCalendar(1987, Calendar.JANUARY, 6).getTime(),
new Float(2.78), new Boolean(GENDER_MALE) },
{ "J", "A", new GregorianCalendar(1989, Calendar.AUGUST, 31).getTime(),
new Float(3.89), new Boolean(GENDER_FEMALE) },
{ "E", "K", new GregorianCalendar(1945, Calendar.JANUARY, 16).getTime(),
new Float(-4.70), new Boolean(GENDER_FEMALE) },
{ "B", "S", new GregorianCalendar(1907, Calendar.AUGUST, 2).getTime(),
new Float(5.00), new Boolean(GENDER_FEMALE) } };
public int getRowCount() {
return values.length;
}
public int getColumnCount() {
return values[0].length;
}
public Object getValueAt(int row, int column) {
return values[row][column];
}
}
public class ExtendsAbstractTableModel extends JFrame {
protected JTable table;
public static void main(String[] args) {
ExtendsAbstractTableModel stt = new ExtendsAbstractTableModel();
stt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
stt.setSize(400, 200);
stt.setVisible(true);
}
public ExtendsAbstractTableModel() {
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
TableValues tv = new TableValues();
table = new JTable(tv);
pane.add(table, BorderLayout.CENTER);
}
}
Get all the table data from DefaultTableModel
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Col1");
model.addRow(new Object[] { "r1" });
model.addRow(new Object[] { "r2" });
model.addRow(new Object[] { "r3" });
// Get all the table data
Vector data = model.getDataVector();
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Insert a row to a table through DefaultTableModel
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Col1");
model.addColumn("Col2");
// Create the first row
model.insertRow(0, new Object[] { "r1" });
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Insert a row to a table through DefaultTableModel at specified row
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Col1");
model.addColumn("Col2");
// Create the first row
model.insertRow(0, new Object[] { "r1" });
// Insert a row at position p
int p = 1;
model.insertRow(p, new Object[] { "r3" });
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Listening to JTable Events with a TableColumnModelListener
The listener will be notified of any addition, removal, movement, or selection of columns, or changing of column margins.
public interface TableColumnModelListener extends EventListener {
public void columnAdded(TableColumnModelEvent e);
public void columnMarginChanged(ChangeEvent e);
public void columnMoved(TableColumnModelEvent e);
public void columnRemoved(TableColumnModelEvent e);
public void columnSelectionChanged(ListSelectionEvent e);
}
TableColumnModelListener tableColumnModelListener =
new TableColumnModelListener() {
public void columnAdded(TableColumnModelEvent e) {
System.out.println("Added");
}
public void columnMarginChanged(ChangeEvent e) {
System.out.println("Margin");
}
public void columnMoved(TableColumnModelEvent e) {
System.out.println("Moved");
}
public void columnRemoved(TableColumnModelEvent e) {
System.out.println("Removed");
}
public void columnSelectionChanged(ListSelectionEvent e) {
System.out.println("Selected");
}
};
Map TableModel
/*
* Project: Gulden Utilies
* Class: de.gulden.util.swing.MapTableModel
* Version: snapshot-beautyj-1.1
*
* Date: 2004-09-29
*
* This is a snapshot version of the Gulden Utilities,
* it is not released as a seperate version.
*
* Note: Contains auto-generated Javadoc comments created by BeautyJ.
*
* This is licensed under the GNU Lesser General Public License (LGPL)
* and comes with NO WARRANTY.
*
* Author: Jens Gulden
* Email: amoda@jensgulden.de
*/
import java.util.*;
import java.util.Map;
import javax.swing.table.AbstractTableModel;
/**
* Class MapTableModel.
*
* @author Jens Gulden
* @version snapshot-beautyj-1.1
*/
public class MapTableModel extends AbstractTableModel {
// ------------------------------------------------------------------------
// --- fields ---
// ------------------------------------------------------------------------
/**
* The map.
*/
protected Map map;
/**
* The column names array.
*/
protected String[] columnNames;
// ------------------------------------------------------------------------
// --- constructors ---
// ------------------------------------------------------------------------
/**
* Creates a new instance of MapTableModel.
*/
public MapTableModel() {
super();
}
/**
* Creates a new instance of MapTableModel.
*/
public MapTableModel(Map map) {
this(map,"Entry","Value");
}
/**
* Creates a new instance of MapTableModel.
*/
public MapTableModel(Map map, String keyName, String valueName) {
this();
setMap(map);
setColumnNames(keyName,valueName);
}
// ------------------------------------------------------------------------
// --- methods ---
// ------------------------------------------------------------------------
/**
* Returns the row count.
*/
public int getRowCount() {
return map.size();
}
/**
* Returns the column count.
*/
public int getColumnCount() {
return 2;
}
/**
* Returns the value at.
*/
public Object getValueAt(int row, int column) {
Object[] entries=map.entrySet().toArray();
Map.Entry entry=(Map.Entry)entries[row];
if (column==0) {
return entry.getKey();
} else if (column==1) { // column==1
return entry.getValue();
} else {
throw new IndexOutOfBoundsException("MapTableModel provides a 2-column table, column-index "+column+" is illegal.");
}
}
/**
* Returns the column name.
*/
public String getColumnName(int column) {
return columnNames[column];
}
/**
* Sets the column names.
*/
public void setColumnNames(String keyName, String valueName) {
String[] names={keyName,valueName};
columnNames=names;
}
/**
* Returns the map.
*/
public Map getMap() {
return map;
}
/**
* Sets the map.
*/
public void setMap(Map _map) {
map = _map;
}
} // end MapTableModel
Move the first row to the end of the table
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Col1");
model.addRow(new Object[] { "r1" });
model.addRow(new Object[] { "r2" });
model.addRow(new Object[] { "r3" });
// Move the first row to the end of the table
model.moveRow(0, 0, model.getRowCount() - 1);
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Move the first two rows to the end of the table
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Col1");
model.addRow(new Object[] { "r1" });
model.addRow(new Object[] { "r2" });
model.addRow(new Object[] { "r3" });
// Move the first two rows to the end of the table
model.moveRow(0, 1, model.getRowCount() - 2);
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Move the last row to the beginning of the table
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Col1");
model.addRow(new Object[] { "r1" });
model.addRow(new Object[] { "r2" });
model.addRow(new Object[] { "r3" });
// Move the last row to the beginning of the table
model.moveRow(model.getRowCount() - 1, model.getRowCount() - 1, 0);
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Move the last two rows to the start of the table
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Col1");
model.addRow(new Object[] { "r1" });
model.addRow(new Object[] { "r2" });
model.addRow(new Object[] { "r3" });
// Move the last two rows to the start of the table
model.moveRow(model.getRowCount() - 2, model.getRowCount() - 1, 0);
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Overwrite the date from the first row with DefaultTableModel
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Col1");
model.addRow(new Object[] { "r1" });
model.addRow(new Object[] { "r2" });
model.addRow(new Object[] { "r3" });
Vector data = model.getDataVector();
Vector row = (Vector) data.elementAt(1);
// Overwrite the first row with the copy
Vector firstRow = (Vector) data.elementAt(0);
for (int i = 0; i < row.size(); i++) {
firstRow.set(i, row.get(i));
}
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Remove the first row from a table with DefaultTableModel
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
model.addColumn("Col1");
model.addRow(new Object[] { "r1" });
model.addRow(new Object[] { "r2" });
model.addRow(new Object[] { "r3" });
// Remove the first row
model.removeRow(0);
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Remove the last row from a table with DefaultTableModel
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
// Create some data
model.addColumn("Col1");
model.addRow(new Object[] { "r1" });
model.addRow(new Object[] { "r2" });
model.addRow(new Object[] { "r3" });
model.removeRow(model.getRowCount() - 1);
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Sample Sorting Table Model
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
class SampleSortingTableModel extends AbstractTableModel implements TableModelListener {
protected TableModel base;
protected int sortColumn;
protected int[] row;
public SampleSortingTableModel(TableModel tm, int sortColumn) {
this.base = tm;
this.sortColumn = sortColumn;
tm.addTableModelListener(this);
rebuild();
}
public Class getColumnClass(int c) {
return base.getColumnClass(c);
}
public int getColumnCount() {
return base.getColumnCount();
}
public String getColumnName(int c) {
return base.getColumnName(c);
}
public int getRowCount() {
return base.getRowCount();
}
public Object getValueAt(int r, int c) {
return base.getValueAt(row[r], c);
}
public boolean isCellEditable(int r, int c) {
return base.isCellEditable(row[r], c);
}
public void setValueAt(Object value, int r, int c) {
base.setValueAt(value, row[r], c); // Notification will cause re-sort
}
public void tableChanged(TableModelEvent event) {
rebuild();
}
protected void rebuild() {
int size = base.getRowCount();
row = new int[size];
for (int i = 0; i < size; i++) {
row[i] = i;
}
sort();
}
protected void sort() { // Sort and notify listeners
for (int i = 1; i < row.length; i++) {
int j = i;
while (j > 0 && compare(j - 1, j) > 0) {
int temp = row[j];
row[j] = row[j - 1];
row[j - 1] = temp;
j--;
}
}
fireTableStructureChanged();
}
protected int compare(int i, int j) {
String s1 = base.getValueAt(row[i], sortColumn).toString();
String s2 = base.getValueAt(row[j], sortColumn).toString();
return s1.rupareTo(s2);
}
}
public class SortableTableModelAbstractTableModel extends JFrame {
DefaultTableModel model = new DefaultTableModel(new Object[][] { { "this", "1" },
{ "text", "2" }, { "will", "3" }, { "be", "4" }, { "sorted", "5" } }, new Object[] {
"Column 1", "Column 2" });
public SortableTableModelAbstractTableModel() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
JTable tableOrig = new JTable(model);
tableOrig.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
JTable tableSorted = new JTable(new SampleSortingTableModel(model, 0));
tableSorted.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
JPanel panel = new JPanel(new GridLayout(1, 2));
panel.add(new JScrollPane(tableOrig));
panel.add(new JScrollPane(tableSorted));
getContentPane().add(panel, BorderLayout.CENTER);
pack();
}
public static void main(String arg[]) {
new SortableTableModelAbstractTableModel().setVisible(true);
}
}
Set table value
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class SetValueAtToSetValue extends JFrame {
public SetValueAtToSetValue() {
final AbstractTableModel model = new MyModel();
final JTable table = new JTable(model);
getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
model.setValueAt(new Integer(1), 0, 0);
JButton button = new JButton("Increment selected cell");
getContentPane().add(button, BorderLayout.SOUTH);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
int column = table.convertColumnIndexToModel(table.getSelectedColumn());
int currentValue = ((Integer) model.getValueAt(row, column)).intValue();
model.setValueAt(new Integer(currentValue + 1), row, column);
}
});
pack();
}
public static void main(String arg[]) {
SetValueAtToSetValue ex2 = new SetValueAtToSetValue();
ex2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ex2.setVisible(true);
}
}
class MyModel extends AbstractTableModel {
private int[][] table = { new int[3], new int[3], new int[3] };
public MyModel() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
table[i][j] = i * j;
}
}
}
public int getColumnCount() {
return table.length;
}
public int getRowCount() {
return table[0].length;
}
public Object getValueAt(int r, int c) {
return new Integer(table[r][c]);
}
public void setValueAt(Object obj, int r, int c) {
table[r][c] = ((Integer) obj).intValue();
fireTableCellUpdated(r, c);
}
}
Sharing a Table Model Between JTable Components
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Main {
public static void main(String[] argv) {
DefaultTableModel model = new DefaultTableModel();
JTable table1 = new JTable(model);
JTable table2 = new JTable(model);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPane.add(new JScrollPane(table1));
splitPane.add(new JScrollPane(table2));
table1.getColumnModel().removeColumn(table1.getColumnModel().getColumn(0));
}
}
Sparsely Populated Table Model
import java.awt.BorderLayout;
import java.awt.Point;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
class SparseTableModel extends AbstractTableModel {
private Map<Point, Object> lookup;
private final int rows;
private final int columns;
private final String headers[];
public SparseTableModel(int rows, String columnHeaders[]) {
this.rows = rows;
this.columns = columnHeaders.length;
headers = columnHeaders;
lookup = new HashMap<Point, Object>();
}
public int getColumnCount() {
return columns;
}
public int getRowCount() {
return rows;
}
public String getColumnName(int column) {
return headers[column];
}
public Object getValueAt(int row, int column) {
return lookup.get(new Point(row, column));
}
public void setValueAt(Object value, int row, int column) {
if ((rows < 0) || (columns < 0)) {
throw new IllegalArgumentException("Invalid row/column setting");
}
if ((row < rows) && (column < columns)) {
lookup.put(new Point(row, column), value);
}
}
}
public class SparseTableModelDemo {
public static void main(String[] a) {
String headers[] = { "A", "B" };
TableModel model = new SparseTableModel(10, headers);
JTable table = new JTable(model);
model.setValueAt("1", 0, 0);
model.setValueAt("2", 9, 0);
model.setValueAt("3", 5, 1);
model.setValueAt("4", 8, 1);
JFrame frame = new JFrame("Fixed Column Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table), BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
Subclass AbstractTableModel to reuse an existing data structure: Treat an array as an AbstractTableModel
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
public class UsingTableModelToContruct {
public static void main(String args[]) {
TableModel model = new AbstractTableModel() {
Object rowData[][] = { { "one", "1" }, { "two", "2" }, { "three", "3" } };
Object columnNames[] = { "English", "#" };
public String getColumnName(int column) {
return columnNames[column].toString();
}
public int getRowCount() {
return rowData.length;
}
public int getColumnCount() {
return columnNames.length;
}
public Object getValueAt(int row, int col) {
return rowData[row][col];
}
};
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame("Resizing Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
The Calendar program.
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
public class Calendar extends JFrame {
String[] years = { "2008", "2009", "2010" };
JComboBox comboBox = new JComboBox(years);
String[] months = { "January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December" };
JList list = new JList(months);
JScrollPane scrollPane = new JScrollPane(list);
CalendarModel model = new CalendarModel();
JTable table = new JTable(model);
public Calendar() {
super();
getContentPane().setLayout(null);
comboBox.setBounds(10, 10, 100, 30);
comboBox.setSelectedIndex(0);
comboBox.addItemListener(new ComboHandler());
scrollPane.setBounds(200, 10, 150, 100);
list.setSelectedIndex(3);
list.addListSelectionListener(new ListHandler());
table.setBounds(10, 150, 550, 200);
model.setMonth(comboBox.getSelectedIndex() + 1998, list.getSelectedIndex());
getContentPane().add(comboBox);
getContentPane().add(scrollPane);
table.setGridColor(Color.black);
table.setShowGrid(true);
getContentPane().add(table);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
setVisible(true);
}
public static void main(String[] args) {
Calendar app = new Calendar();
}
public class ComboHandler implements ItemListener {
public void itemStateChanged(ItemEvent e) {
model.setMonth(comboBox.getSelectedIndex() + 1998, list.getSelectedIndex());
table.repaint();
}
}
public class ListHandler implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
model.setMonth(comboBox.getSelectedIndex() + 1998, list.getSelectedIndex());
table.repaint();
}
}
}
class CalendarModel extends AbstractTableModel {
String[] days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
int[] numDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
String[][] calendar = new String[7][7];
public CalendarModel() {
for (int i = 0; i < days.length; ++i)
calendar[0][i] = days[i];
for (int i = 1; i < 7; ++i)
for (int j = 0; j < 7; ++j)
calendar[i][j] = " ";
}
public int getRowCount() {
return 7;
}
public int getColumnCount() {
return 7;
}
public Object getValueAt(int row, int column) {
return calendar[row][column];
}
public void setValueAt(Object value, int row, int column) {
calendar[row][column] = (String) value;
}
public void setMonth(int year, int month) {
for (int i = 1; i < 7; ++i)
for (int j = 0; j < 7; ++j)
calendar[i][j] = " ";
java.util.GregorianCalendar cal = new java.util.GregorianCalendar();
cal.set(year, month, 1);
int offset = cal.get(java.util.GregorianCalendar.DAY_OF_WEEK) - 1;
offset += 7;
int num = daysInMonth(year, month);
for (int i = 0; i < num; ++i) {
calendar[offset / 7][offset % 7] = Integer.toString(i + 1);
++offset;
}
}
public boolean isLeapYear(int year) {
if (year % 4 == 0)
return true;
return false;
}
public int daysInMonth(int year, int month) {
int days = numDays[month];
if (month == 1 && isLeapYear(year))
++days;
return days;
}
}