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
3
votes
4 answers

JTable removing row gives ArrayOutofBounds exception -1

I have been browsing numerous sites about this and tried some different things but im stumped. Would be grateful for some help. The condition is working that checks if a checkbox is selected (true) but soon as I do model.removeRow(row) it gives me…
Sam
  • 33
  • 1
  • 3
3
votes
1 answer

JTable does not save edit changes

I want to design this JTable. The goal is the user to be able to edit the cells by double clicking on them. Any changes should be able to be saved and stored on a database later. My code is the following: public class BirthGUI extends JFrame…
lephleg
  • 1,724
  • 2
  • 21
  • 41
3
votes
1 answer

How to change rows with columns in JTable?

I have created my JTable like this: String[] columns = {"Country", "Continent", "Latitude", "Longitude"}; String[][] data = {{"A","B","C","D"}}; table = new JTable(data,columns); JScrollPane spTable = new…
MichalB
  • 3,281
  • 6
  • 32
  • 46
3
votes
2 answers

Java, change a cell content as a function of another cell in the same row

I need some help for my problem. I have a table with e.g. a double column and a string column. If the value in the double column is negativ, the string should be "negativ". And the other way if the value is positiv, the string should be…
saduino
  • 65
  • 1
  • 5
3
votes
2 answers

Java JTable, how to change cell data (write text in)?

Am looking to change a cell's data in a jtable. How can I do this? When I execute the following code I get errors. JFrame f= new JFrame(); final JTable table= new JTable(10,5); TableModelListener tl= new TableModelListener(){ public void…
3
votes
1 answer

Jtable/JScrollPanel won't refresh (update data)

I have setup a JTable with paging - which works very well, but I have a problem with updating data to the table. table.repaint() is not working. Here is the code that I am using. Thanks in advance! String[][] data = new String[100][4]; String[]…
ZhiZha
  • 143
  • 2
  • 4
  • 13
3
votes
1 answer

Java Swing - inform GUI about changes to the model

I have a column in JTable that binds to the underlying boolean property on a list of business objects. I also have a combobox, which should select which items should be selected. I basically added the following code as a handler to the combobox: …
Bober02
  • 15,034
  • 31
  • 92
  • 178
3
votes
2 answers

jtable custom model

I'm fighting with a implementation of a jTable. I created my own TableModel class. And there is the problem. Somehow my tableData array (ArrayList of Obejct[]) is not being written correctly. At the end I get a table where all the rows are having…
user1511924
  • 53
  • 1
  • 6
3
votes
1 answer

Java tablemodel for multiple sets of data

I'm currently building a Java GUI application and I'm about to implement something that seemingly requires a great deal of thinking, at least for someone as relatively inexperienced as me. The situation is as follows: I have a class Customer at…
MarioDS
  • 12,895
  • 15
  • 65
  • 121
2
votes
2 answers

Number Format in Jtable

I have a Jtable (tableSummary). I need to format 2 columns of the table so it's content is in DECIMAL form (e.g. 1,400.00) How can i do it? here's my code for the table: private void tableMarketMouseClicked(java.awt.event.MouseEvent evt) { …
zairahCS
  • 325
  • 5
  • 11
  • 17
2
votes
1 answer

JTable Filtering Issue

Here is my scenario: I have 3 views on an application, 2 of which are identical save for 1 thing - one has additional filtering. All of the views are using the same model because they display the same data in (somewhat) different ways. The 2 similar…
paradox870
  • 2,152
  • 4
  • 20
  • 30
2
votes
2 answers

How to clear data from a JTable?

I am programming at Netbeans, and I have a jTable in a frame. In which I load data that occupies a lot of rows, but then i load another table that has a lot less rows. And when i am running it, and loading the 2nd table, the extra rows that the…
Ignacio Nimo
  • 65
  • 3
  • 3
  • 9
2
votes
2 answers

Same dataset, two different JTables

I have some data I have to show through two JTables; the data is the same, but each table will have to show it a little differently. Also, I receive the data from an external connection (JMS in this case, but it doesn't really matter, it could be a…
mdm
  • 3,928
  • 3
  • 27
  • 43
2
votes
1 answer

Java: Observer pattern and garbage collector

i have implemented a TableModel whose registers launch PropertyChangeEvents. My TableModel listen those events to fire TableModelEvents in order to refresh the underliying JTable. If the TableModel is cleared or refreshed with new registers... has…
Telcontar
  • 4,794
  • 7
  • 31
  • 39
2
votes
1 answer

How to save JTable data on JMenuItem click

What I already have is a JTable with a MyTableModel table model attached to it. I have a tableChanged() method that writes table data to a data.csv file at the time a table cell is modified. This means that table data is written to the file every…
aleksejjj
  • 1,405
  • 2
  • 18
  • 28
1 2
3
26 27