Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the proper event for changes in any cell of JTable?

Tags:

java

swing

jtable

I have a simple JTable, there are two columns that matter: quantity and value (Integers). Each time user enters a new row or updates one, each rows value must be multiplied by quantity, results sumed together and the result sum displayed in a JLabel outside the JTable. Looks pretty simple. Except that I have no idea what event should I look for. Something like "cell value changed"? When I right click on the JTable in NetBeans I see no such event or dont recognize it ;) Anyway, before I come up with some weird noobish solution I thought I might ask here what's the proper way to do it :)

like image 239
Sejanus Avatar asked Jan 14 '10 05:01

Sejanus


People also ask

How do you make a JTable cell editable?

jTableAssignments = new javax. swing. JTable() { public boolean isCellEditable(int rowIndex, int colIndex) { return editable; }};

How is JTable created?

JTable(): A table is created with empty cells. JTable(int rows, int cols): Creates a table of size rows * cols. JTable(Object[][] data, Object []Column): A table is created with the specified name where []Column defines the column names.

What is JTable function?

The JTable is used to display and edit regular two-dimensional tables of cells. See How to Use Tables in The Java Tutorial for task-oriented documentation and examples of using JTable .

How can I tell if a row is selected in JTable?

So you can call table. getSelectionModel(). isSelectionEmpty() to find out if any row is selected.


2 Answers

you should add a TableModelListener as described here.

also, in your listener once you've updated the value of the other cell values programatically you will need to call model.fireTableCellUpdated to let swing know about the changes

like image 175
pstanton Avatar answered Oct 13 '22 12:10

pstanton


Finally I managed to find how to do it in NetBeans with all the code protection, et cetera. It's right click on JTable in Design View, Properties, then Code tab, and then add your code in Pre-Adding Code section (code evaluated before table is added to container or something like that).

The exact code which works for me is this:

table.getModel().addTableModelListener(
new TableModelListener() 
{
    public void tableChanged(TableModelEvent evt) 
    {
         // here goes your code "on cell update"
    }
});

I am aware that Tom, above, suggested never calling getModel() but I'm too new to Java to understand why (care to explain, please..?) :) and it's just an example anyway, I'm adding this answer just to show how to do it in NetBeans (thanks pstanton for answering what to do). Because I found so many people asking this in internet and no real answers (apart from "copy your protected code out of NetBeans protected area and then customize your table).

like image 3
Sejanus Avatar answered Oct 13 '22 12:10

Sejanus