JTable removeRow(), removing wrong row - java

I have a JTable and I need to remove a row, namely, the selected row.
So first, I get the the table model :
DefaultTableModel model = (DefaultTableModel) table.getModel();
Then the selected row (if the second row is selected, this returns 1, which is understandable because rows start from zero):
int selectedRow = table.getSelectedRow();
Then I try to remove the row:
model.removeRow(selectedRow);
Then I set the table model again:
table.setModel(model);
What this achieves is removing a completely random row. I simply can't understand why. I have sorted the table at some point, using table.setRowSorter(sorter), but I don't know why that should be a problem. If an SSCCE is absolutely needed please let me know, because I have a lot of code to modify before I can produce one.
NOTE: The values returned by these two lines differ:
System.out.println(table.getValueAt(selectedRow, 1));
System.out.println(model.getValueAt(selectedRow, 1));

If is JTable filtered or sorted then you can convert
int modelRow = convertRowIndexToModel(row);

The index returned by JTable.getSelectedRow is a view index : it's the index of the row as seen by the end-user in the table. It's not the same as the model index, because if you sort the table, the indices in the model don't change, but the indices in the view do change. So, you must always use JTable.convertRowIndexToModel to get the model index from the view index.
Note that the same must be done for columns, because the user might choose to reorder columns to its taste.
Also, you shouldn't have to set the model again each time you remove a row. Instead, your model should fire a TableModelEvent to inform the view about the removal. See AbstractTableModel.fireTableRowsDeleted.

Related

JTable values not refreshed after tables is sorted

I have JTable object, filled with data provided from my implementation of AbstractTableModel. I have mouse event listener and when I click on some cell I get its row and column position. With this values I call getValueAt(int row, int column) method from TableModel and I get my data. The problem is the data in the table can be sorted when I click on column name. When again I try to call getValueAt() I get the old value
Example:
col1|col2
val11|val21
val12|val22
When I click on col1
values are:
col1|col2
val12|val22
val11|val21
The I call getValueAt(0,0) and still get val11, and I should get val12. How can I fix this ? Thanks!
The row index in the view (that you probably get from your mouse listener - if you posted the code as requested, we would know instead of having to guess) is not the same as the row index in the model, once the table is sorted. To convert from the view index to the model index, use convertRowIndexToModel().
Note that the same care must be taken for columns, as the user can reorder them by drag and dropping them.
I've manage to do it. table.getValueAt() should be called direct to the table object. My previous attempt was table.getModel().getValueAt().

How to select the last inserted row in a JTable?

I have a JTable with two columns and a table model that uses a class which works with a hash map. The elements of this map are the table rows.
Every time I add a new element I need the element to be selected, regardless of any sorting. Now, I've tried using the following method:
int lastRow = table.convertRowIndexToView(tableModel.getRowCount() - 1);
table.setRowSelectionInterval(lastRow, lastRow);
The problem is, this works only when I'm adding data in a sorted fashion (e.g. "A", "B", "C" and not even then since "D", for example, is placed ahead of A once added). Could someone tell me how to solve this problem?
The problem is most likely in your TableModel, since the code you posted is just fine. You mention you use a HashMap for storing the data of your TableModel. Problem with a HashMap is that it hasn't any ordering. Adding an element to it might alter the order in which you get the elements in the map.
Better to use a data structure which respects the ordering.
better could be to use prepareRendered for hightlighting max row index from XxxTableModel
JTable could be Sorted and Filtered too, then last added row couldn't be visible in JTables view
depends of ListSelectionMode, but by default you can do
table.setRowSelectionInterval(lastRow, lastRow);
table.setColumnSelectionInterval(columnMinIndex, columnMaxIndex);
for better help sooner post an SSCCE, short, runnable, compilable, just about JFrame, JTable in JScrollPane and a new addRow fired from swing.Timer

Get values of all columns in selected JTable row

so I have a application in which I have a JTable filled with values related to a process list on a computer (so it has things like process name, PID, memory offset, etc). As part of this I want to collect the process name and PID when a user clicks on a row for a certain process--but how do I do this? If I call "table.getSelectedRows()" or "table.getSelectedColumns()" with a row selected I just get one element representing the clicked field's column or row index. Thanks for any help.
You can get the data for each cell in the row by calling table.getValueAt(row, column) once for each column, with 'row' being the selected row index and the 'column' being the column's zero-based index.
Note that this can be somewhat problematic, however, because the user can re-order the columns, and this method references the column in display-order.
The better way to do this is to reference the JTable's TableModel via table.getModel(), and then using the TableModel's getValueAt() method to get the columns in model order (which does not change when the columns are re-ordered in the view).

How can I hide a row in my JTable?

I'm using Eclipse Indigo SR1 with JDK 1.7, on Windows 7 Pro.
I've written a desktop app, Swing based.
My app includes a JTable; it shows many records of type T, one row per record.
The table model points to Vector vect, named vect, containing all data to be shown in the JTable.
The app includes a combo, named sele, showing three values: 0, 1, 2.
When sele = 0, every record of vect has to be visible in the JTable.
When sele = 1, the JTable has to show only vect records having odd row index and all records with even row index mustn't be visible. Viceversa, when sele = 2.
So, here's my question: how can I make a row not visible in the JTable ?
I can't use the table model, because it points to vect that contains "all" data.
I tried a table cell renderer, but it seems that you can set the color of a cell, but you can't set it not visible or modify its size.
I've tried another way: if r is the row index, and I want that row to be not visible, I write table.setRowHeight(r,0), but this instruction throws an exception, the height can't be set to zero.
I could solve the problem by splitting the data, dividing vect in two, but I don't like that.
Does anybody have an idea ?
thanx in advance,
William
PS: someone told me to create a filtering TableModel that wraps the existing TableModel. The filtering model would be sensitive to the filtering criteria and fire the appropriate methods (TableDataChanged) when the filter was changed. The getRowCount method would return the filtered count. The getValueAt method would map the filtered row to the actual row in the underlying TableModel.
Mah, perhaps it's a good idea, but frankly I'm not able to understand it...
Use a TableRowSorter - which is:
An implementation of RowSorter that provides sorting and filtering using a TableModel. ..
See How to Use Tables & especially Sorting and Filtering for more info.

How to insert a column at a specific position in JTable

I have a JTable with a predefined model
how to ask the model to insert a specific column in a specific position ?
so i want something like : DefaultTableModel.insertRow(int,Object[]) for columns
There is no insertColumn method like DefaultTableModel.insertRow() for inserting rows. In order to insert a column at a particular position, you must append the column using DefaultTable.addColumn() and then move the new column into the desired position.
JTable table = new JTable(rows, cols);
table.setAutoCreateColumnsFromModel(false);
DefaultTableModel model = (DefaultTableModel)table.getModel();
TableColumn col = new TableColumn(model.getColumnCount());
col.setHeaderValue(headerLabel);
table.addColumn(col);
model.addColumn(headerLabel.toString(), values);
table.moveColumn(table.getColumnCount()-1, vColIndex);
Is it really necessary to add the column in your TableModel at a specific index ? You can more easily adjust the column order in the view (the JTable) as documented in the class javadoc of JTable
By default, columns may be rearranged in the JTable so that the view's columns appear in a different order to the columns in the model. This does not affect the implementation of the model at all: when the columns are reordered, the JTable maintains the new order of the columns internally and converts its column indices before querying the model.
This is achieved by using the JTable#moveColumn method.
Adding a column to your DefaultTableModel is done calling the DefaultTableModel#addColumn method
With DefaultTableModel:
At the end one has to call fireDataChanged. There is only an addColumn with several overloads. This is no hindrance as the order of display is independent. One may move a column to another position, and has to take care of view index != column index. To get the correct view index immediately after adding the column, one has to access the JTable and call moveColumn.
I found it at times easier to create a new TableModel and assign that. Or not use the DefaultTableModel.
this link may help
http://www.roseindia.net/java/example/java/swing/InsertColumn.shtml
public void positionColumn(JTable table,int col_Index) {
table.moveColumn(table.getColumnCount()-1, col_Index);
}

Categories