JTable sorting not the good value in the cell - java

I am using NetBeans to write a program. I create a JTable with the design and I add rows to the table without any problem.
When I click on the tab to sort the table it works, with setAutoCreateRowSorter(true). However when I try to get the value of the updated cell it is not the good one. Indeed, it is the value of the previous cell, when I fill my table.
This is how I add row to my table:
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);
for (int i = 0; i < arrayPep.size(); i++) {
model.addRow(new Object[]{arrayPep.get(i).getPeptide(), arrayPep.get(i).getStart(), arrayPep.get(i).getStop(), arrayPep.get(i).geteValue(), arrayPep.get(i).getName()});
}
This is how I try to get the value of the cell:
DefaultTableModel model = (DefaultTableModel) table.getModel();
table.getModel().getValueAt(rowSelected, 0);
How could I fix this ?

You are indexing the model with an index from the view. First convert the view index to a model index using JTable.convertRowIndexToModel(rowSelected):
int modelRowSelected = table.convertRowIndexToModel(rowSelected);
table.getModel().getValueAt(modelRowSelected, 0);
For some context regarding view indexes and model indexes, please read this answer I gave on the topic.

Related

JTable becomes blank after executing update on table? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to write some software where when a user adds a new entry to a SQL database, my JTable showing the entries in the database updates. Currently, when the method updateTable(Object[][] data) is called, it results in the table becoming blank.
Would anyone know of a fix for this type of issue?
Here is the code for the method:
/**
* This method updates the JTable which shows the Amp Settings.
*
* #param data A 2D Array of Objects witch represents the data in the
* database.
*/
private void updateTable(Object[][] data)
{
// A new DefaultTableModel.
DefaultTableModel dtm = new DefaultTableModel();
// Looping over the data, create a new row and add it to the DataModel.
for (int i = 0; i < data.length; i++)
{
Object[] row = new Object[data[i].length];
// Fill the row's data.
for (int j = 0; j < row.length; j++)
{
row[j] = data[i][j];
}
// Set the row in the table model.
dtm.addRow(row);
}
// Set the model of the table to the newly created DefaultTableModel.
table.setModel(dtm);
((AbstractTableModel) table.getModel()).fireTableDataChanged();
}
Here is the code which calls updateTable():
// Calls update table, SERVER.dbtoArray() returns a 2D Array of objects.
updateTable(SERVER.dbToArray());
DefaultTableModel dtm = new DefaultTableModel();
Even though you add data to the TableModel you didn't add any column names so as far as the table is concerned there are 0 columns to display.
Your code should be something like:
String[] columnNames = { "Column1", "Column2", "..." );
DefaultTableModel dtm = new DefaultTableModel(columnNames, 0);
Or a better approach would be to use:
DefaultTableModel dtm = (DefaultTableModel)table.getModel();
dtm.setRowCount(0);
This will keep the existing columns and just add the data.
Also you don't need to recreate the row array. You already have the data as a row in your 2D array:
for (int i = 0; i < data.length; i++)
{
Object[] row = data[i];
model.addRow( row );
}

After sorting a jtable how can I number a column?

Hello am developing a Java Desktop result system I have succeeded in sorting my J table with respective to the column average Am still trying to give positions to the students after the J table has been sorted so that each student gets his or her position basing on his or her average this is what I have done so far..`
//Sorts j Table basing on column average
public void checkPosition(){
//Erases column s/no
jTable1.getColumnModel().getColumn(0).setMinWidth(0);
jTable1.getColumnModel().getColumn(0).setMaxWidth(0);
jTable1.getColumnModel().getColumn(0).setWidth(0);
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(jTable1.getModel());
jTable1.setRowSorter(sorter);
List<RowSorter.SortKey> sortKeys = new ArrayList<>(2000);
sortKeys.add(new RowSorter.SortKey(jTable1.getColumnCount()-2, SortOrder.DESCENDING));
//sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);
positionInsert();
}
public void positionInsert(){
//Inserts position at last column "position"
int pos=1;
for(int g=0; g<jTable1.getRowCount(); g++){
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setValueAt(pos, g, jTable1.getColumnCount()-1);
pos++;
}
}
However it still doesn't work the position is still faulty Screenshot of j table
The table is seen at the link above my english is not that good but help will be much appreciated thanks
When you sort a table the data in the table model doesn't change, only the order in which the data is displayed in the table.
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setValueAt(pos, g, jTable1.getColumnCount()-1);
The above code assumes that the data in the model is in the same order as the table which is wrong when you sort of filter a table.
You need to update the data in the model via the table:
table.setValueAt(pos, g, jTable1.getColumnCount()-1);
The table will now convert the row of the table to the row of the model before updating the model.
Or if you want to update the model directly, you are responsible for converting the table row to the model row. This is done by using the convertViewToModel(...) method of the JTable.

Increase row count in a JTable

I'm developing an address book for my classmates but I'm having a problem with a JTable. Here you can see a preview of the program, I'm using NetBeans [click]. If you click Add to the Address Book, the program adds a new row in that table and fills its cells with the data located in text fields below. I'm using the following code but the row count doesn't increase.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
int h;
DefaultTableModel model = new DefaultTableModel();
h=jTable1.getRowCount()+1;
model.setRowCount(h);
jTable1.setValueAt(jTextField2.getText(), h, 1);
jTable1.setValueAt(jTextField3.getText(), h, 2);
//I'll use more setValueAt() because I must fill all the cells
}
Could you give me some advice as to how to fix this problem?
You created a new model. You should take the model that is assigned to the table.
DefaultTableModel model = new DefaultTableModel();
should be:
DefaultTableModel model = jTable1.getModel();

How to use hidden column data of jTable in tooltip

I am trying to display the data of hidden column as tooltip. Hiding is working perfectly using the following code:
JTable table = new JTable(model){
//Implement table cell tool tips.
public String getToolTipText(MouseEvent e) {
String tip = null;
java.awt.Point p = e.getPoint();
int rowIndex = rowAtPoint(p);
int colIndex = columnAtPoint(p);
int realColumnIndex = convertColumnIndexToModel(colIndex);
try {
tip = getValueAt(rowIndex, 8).toString();
} catch (RuntimeException e1) {
//catch null pointer exception if mouse is over an empty line
}
return tip;
}
};
TableColumnModel tcm = table.getColumnModel();
TableColumn tc;
for(int i = 1; i <= 7; i++){
tc = tcm.getColumn(8);
tcm.removeColumn(tc);
}
But the tooltip is not showing the data of hidden column (getValue function is not returning value). So do hiding the column delete the data as well ?
You do not need to for loop as you do not use the i variable ;-)
The removeColumn on the JTable does not remove the data from the model, as clearly stated in the javadoc
Removes aColumn from this JTable's array of columns. Note: this method does not remove the column of data from the model; it just removes the TableColumn that was responsible for displaying it.
There is no mention in the javadoc for the same method on the TableColumnModel, but I would assume it works the same way, but you can always give it a try to call it on the JTable instead
The real problem in your code is the use of getValueAt, which uses the row and column index of the table, and not of the model
Note: The column is specified in the table view's display order, and not in the TableModel's column order. This is an important distinction because as the user rearranges the columns in the table, the column at a given index in the view will change. Meanwhile the user's actions never affect the model's column ordering.
And since you removed that column, it simply does not exists for the table. Call the getValue method on the model instead, and do not forget to convert the row index

Retrieving JTable line content after user sorted content by clicking on column

I have a pane with two tables A and B. When a row is selected in A, the content of B should be upated.
My code detects row selections in A fine. But, when the user clicks on the column header to sort rows, it does not seem like this is taken into account in A's table model.
So, I can get the selected row number (which is correct considering the sorting), but when I try to retrieve row field content from A using its table model, it gives me the values as if rows had not been sorted.
How can I retrieve the content of the selected line from the selected row number?
Without any code, it is hard to say for sure what your problem is. However, it sounds like you are mixing up the row indices between the view and the model. You must be very clear about what co-ordinate system you are referring to (view or model) when you have a row number. See the JTable API for the convertRowIndexToModel and convertRowIndexToView methods.
You probably need something like this:
JTable table = ...;
TableModel model = ...;
int viewRow = table.getSelectedRow();
int modelRow = table.convertRowIndexToModel(viewRow);
int viewColumn = table.getSelectedColumn();
int modelColumn = table.convertColumnIndexToModel(viewColumn);
Object cell = model.getValueAt( modelRow, modelColumn );

Categories

Resources