Questions tagged [tablemodel]

Table model is attached to Java Swing JTable, providing content to the table, and accepting the cell editing events from the table.

TableModel is an interface included in javax.swing.table package, which defines a contract to work with JTable component. This interface provides methods to handle table's content, accepting cell editing events and data event support through TableModelListener interface.

There are two known implementations: AbstractTableModel and DefaultTableModel. First one is an abstract implementation which provides full event handling and several default implementation for methods related to table's content. Second one is a full implementation based on AbstractTableModel.

Developers has the ability to create their own implementation of TableModel interface, either by extending AbstractTableModel or by implementing the whole interface from the scratch. An example is shown in Creating a Table Model section of How to Use Tables official tutorial.

Here is an example of implementation by extending AbstractTableModel, intended to be used with user-defined POJO objects.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.table.AbstractTableModel;

/**
 * Abstract base class which extends from {@code AbstractTableModel} and 
 * provides an API to work with user-defined POJO's as table rows. Sub-classes 
 * extending from {@code DataObjectTableModel} must implement 
 * {@code getValueAt(row, column)} method. 
 * 
 * By default cells are not editable. If those are intended to be editable then 
 * sub-classes should override both {@code isCellEditable(row, column)} and 
 * {@code setValueAt(row, column)} methods.
 * 
 * Finally, it is not mandatory but highly recommended to override 
 * {@code getColumnClass(column)} method, in order to return the appropriate 
 * column class: default implementation always returns {@code Object.class}.
 * 
 * @param <T> The data object's class handled by this TableModel.
 */
public abstract class DataObjectTableModel<T> extends AbstractTableModel {

    private final List<String> columnNames;
    private final List<T> data;

    public DataObjectTableModel() {
        this.data = new ArrayList<>();
        this.columnNames = new ArrayList<>();
    }

    public DataObjectTableModel(List<String> columnIdentifiers) {
        this();
        if (columnIdentifiers != null) {
            this.columnNames.addAll(columnIdentifiers);
        }
    }

    @Override
    public int getRowCount() {
        return this.data.size();
    }

    @Override
    public int getColumnCount() {
        return this.columnNames.size();
    }

    @Override
    public String getColumnName(int columnIndex) {
        return this.columnNames.get(columnIndex);
    }

    public void setColumnNames(List<String> columnNames) {
        if (columnNames != null) {
            this.columnNames.clear();
            this.columnNames.addAll(columnNames);
            fireTableStructureChanged();
        }
    }

    public List<String> getColumnNames() {
        return Collections.unmodifiableList(this.columnNames);
    }

    public void addRow(T dataObject) {
        int rowIndex = this.data.size();
        this.data.add(dataObject);
        fireTableRowsInserted(rowIndex, rowIndex);
    }

    public void addRows(List<T> dataObjects) {
        if (!dataObjects.isEmpty()) {
            int firstRow = data.size();
            this.data.addAll(dataObjects);
            int lastRow = data.size() - 1;
            fireTableRowsInserted(firstRow, lastRow);
        }
    }

    public void insertRow(T dataObject, int rowIndex) {
        this.data.add(rowIndex, dataObject);
        fireTableRowsInserted(rowIndex, rowIndex);
    }

    public void deleteRow(int rowIndex) {
        if (this.data.remove(this.data.get(rowIndex))) {
            fireTableRowsDeleted(rowIndex, rowIndex);
        }
    }

    public T getDataObject(int rowIndex) {
        return this.data.get(rowIndex);
    }

    public List<T> getDataObjects(int firstRow, int lastRow) {
        List<T> subList = this.data.subList(firstRow, lastRow);
        return Collections.unmodifiableList(subList);
    }

    public List<T> getDataObjects() {
        return Collections.unmodifiableList(this.data);
    }

    public void clearTableModelData() {
        if (!this.data.isEmpty()) {
            int lastRow = data.size() - 1;
            this.data.clear();
            fireTableRowsDeleted(0, lastRow);
        }
    }
}
404 questions
95
votes
6 answers

JTable How to refresh table model after insert delete or update the data.

This is my jTable private JTable getJTable() { String[] colName = { "Name", "Email", "Contact No. 1", "Contact No. 2", "Group", "" }; if (jTable == null) { jTable = new JTable() { public boolean…
user236501
  • 8,538
  • 24
  • 85
  • 119
21
votes
5 answers

Java JTable getting the data of the selected row

Are there any methods that are used to get the data of the selected row? I just want to simply click a specific row with data on it and click a button that will print the data in the Console.
ZeroCool
  • 437
  • 1
  • 7
  • 23
16
votes
7 answers

Preserve JTable selection across TableModel change

We're seeing JTable selection get cleared when we do a fireTableDataChanged() or fireTableRowsUpdated() from the TableModel. Is this expected, or are we doing something wrong? I didn't see any property on the JTable (or other related classes) about…
John M
  • 13,053
  • 3
  • 27
  • 26
12
votes
4 answers

How to implement dynamic GUI in swing

First of all, apologies for posting something perhaps a bit excessively specific, but I'm not very experienced with Swing, and can't seem to find good examples that fit my needs. So I'm trying to figure out the best way to implement the a dynamic…
Rolf
  • 2,178
  • 4
  • 18
  • 29
10
votes
4 answers

What is the best way to listen for changes in JTable cell values and update database accordingly?

I'm building and app with multiple JTables and I need to detect when cell value change occurs so I can update it in the database. I tried TableModelListener and overriding tableChanged, but it fires only when I click away (click on another row)…
Igor
  • 1,532
  • 4
  • 23
  • 44
9
votes
4 answers

Removing Column from TableModel in Java

In Java I'm using the DefaultTableModel to dynamically add a column to a JTable. //create DefaultTableModel with columns and no rows DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0); JTable table = new JTable(tableModel); The…
Mark
  • 93
  • 1
  • 1
  • 4
9
votes
3 answers

Moving a row in jTable

How can one move a row in jTable so that row1 goes to row2's position and row2 goes to row1's position ?
Attilah
  • 17,632
  • 38
  • 139
  • 202
8
votes
4 answers

Why Java DefaultTableModel use Vector?

I know we have to use AWT thread for all table model update operations. Under the single AWT thread, any table model will be thread-safe. Why DefaultTableModel picks thread-safe Vector as its data stucture, which slower than other data structures…
user729309
  • 81
  • 1
  • 2
8
votes
1 answer

How to set a custom object in a JTable row

I should tell this first, this is NOT about Rendering a Table cell. Here is the TableModel that i'm building using a 2D array based on a User object in my DB. List userList = userManagerService.getAllUsers(); /* String[] col_user =…
shan
  • 1,164
  • 4
  • 14
  • 30
7
votes
2 answers

Java: Possible to replace TableModel in an existing JTable?

Is it possible to replace the entire TableModel in an existing JTable or do I have to recreate the JTable?
opike
  • 7,053
  • 14
  • 68
  • 95
7
votes
3 answers

create TableModel and populate jTable dynamically

I want to store the results of reading lucene index into jTable, so that I can make it sortable by different columns. From index I am reading terms with different measures of their frequencies. Table columns are these : [string term][int…
Julia
  • 1,217
  • 8
  • 23
  • 46
6
votes
3 answers

Get Selected Value from JXTreeTable

I am building a treetable using JXTreeTabble and I want to disable/able menu items depending on the selected value. So, I tried to put this code in my table model: public Object getValueAt(int index) { if (index >= 0 && index <…
user276002
  • 178
  • 3
  • 10
6
votes
4 answers

ArrayList of arrays vs. array of ArrayLists vs. something similar

I'm creating a TableModel which will have a fixed number of columns, but the number of rows will be changing (mostly, increasing as function of time). Which would be better approach to store the data, ArrayList[] columns = new…
Joonas Pulakka
  • 36,252
  • 29
  • 106
  • 169
5
votes
3 answers

How to set icon in a column of JTable?

I am able to set the column's header but not able to set icon in all the rows of first column of JTable. public class iconRenderer extends DefaultTableCellRenderer{ public Component getTableCellRendererComponent(JTable table,Object obj,boolean…
bsm
  • 1,793
  • 11
  • 30
  • 41
5
votes
2 answers

Cell validation in JTable

I have a JTable that needs cell validation for the cells where the user can input text. When a user enters invalid text the border of the cell turns red. I've managed to get this working associating a two dimension array to flag if each cell has…
xgon
  • 175
  • 1
  • 3
  • 11
1
2 3
26 27