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 :)
jTableAssignments = new javax. swing. JTable() { public boolean isCellEditable(int rowIndex, int colIndex) { return editable; }};
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.
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 .
So you can call table. getSelectionModel(). isSelectionEmpty() to find out if any row is selected.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With