JTable getSelectedRow does not return the selected row index
Look to your code
private void jbInit() throws Exception {
...
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPane1, null);
jTable1 = new JTable (model);
...
You add jTable1
to the JScrollPane
at first and only then you create jTable1
. It's incorrect way. jTable1
variable doen't linked now with table you place at the form. I think it's cause of your problem.
Move creation of the jTable1
before adding in into JScrollPane
.
...
jTable1 = new JTable (model);
jScrollPane1.getViewport().add(jTable1, null);
this.getContentPane().add(jButton2, null);
this.getContentPane().add(jButton1, null);
this.getContentPane().add(jScrollPane1, null);
...
JTable not returning selected row correctly
you shouldnt reinitialize your table with a new JTable after you call replace. the fireTableDataChanged() method will alert your existing table that it should repaint. what is happening is that you are looking at the table that you put into the panel, but you are changing the variable to a different instance of JTable. When you query that new, but not visible table, it will give you -1 for the selected row count. it might be helpful if you edit your post to display what is going on in that area of the code.
2nd edit:
instead of this:
if(model==null)
model = new AchievementTableModel(cells, columns);
else
model.replace(cells, columns);
if(table==null) {
table = new JTable(model);
table.setFillsViewportHeight(true);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getTableHeader().setReorderingAllowed(false);
table.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
table.getColumnModel().setColumnSelectionAllowed(false);
table.getTableHeader().setResizingAllowed(false);
} else
table.setModel(model);
column = table.getColumn(columns[0]);
column.setPreferredWidth(25);
column = table.getColumn(columns[1]);
column.setPreferredWidth(225);
column = table.getColumn(columns[2]);
column.setPreferredWidth(40);
table.doLayout();
add(new JScrollPane(table), BorderLayout.CENTER);
do this instead:
if(model==null) {
model = new AchievementTableModel(cells, columns);
} else {
model.setDataVector(cells, columns);
}
if(table==null) {
table = new JTable(model);
table.setFillsViewportHeight(true);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getTableHeader().setReorderingAllowed(false);
table.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
table.getColumnModel().setColumnSelectionAllowed(false);
table.getTableHeader().setResizingAllowed(false);
column = table.getColumn(columns[0]);
column.setPreferredWidth(25);
column = table.getColumn(columns[1]);
column.setPreferredWidth(225);
column = table.getColumn(columns[2]);
column.setPreferredWidth(40);
table.doLayout();
add(new JScrollPane(table), BorderLayout.CENTER);
} else {
table.setModel(model);
}
you dont need to add the table to a new scrollpane and re-add it to the panel on each model change.
JTable.getSelectedRow() is returning -1
Get the row index using the event, not the table selection:
final int selectedRowIndex = table.rowAtPoint(mouseEvent.getPoint());
// If the rows are sorted or filtered
final int modelRowIndex = table.convertRowIndexToModel(selectedRowIndex);
getSelectedRow()
would not work with multiple selected rows (multiple selections allowed), as it will always return "the index of the first selected row".
Jtable get selected row always returns -1
The reason why you are getting -1
from getSelectedRow()
even though you seem to have "added a row" is, because the Frontend
object you are calling checkActiveItem()
on is a completely different Frontend
object than the one you are seeing.
The issue is here, inside of your Timer
s run()
:
Frontend f = new Frontend();
You create a new Frontend
object for each timer iteration. And you call checkActiveItem()
on exactly this object, not on the frontend you are seeing and pressing buttons on. Hence, the incorrect output.
As a solution, don't create new Frontend
s, instead, call checkActiveItem()
on your original frontend object, which you made visible.
Java - JTable - Wrong data in getSelectedRow()
You are incorrectly using a view-index to index the model. The problems in your code:
- Your inner
for
loop should look like this:
int rowModelId = convertRowIndexToModel( row );
for (int c = 0; c < headerCols.size(); c++) {
newRow.put(
headerCols.get(c),
(String) tableModel.getValueAt(rowModelId, c)
);
}
- Deleting the rows should be done like this:
while(table.getSelectedRow() != -1) {
int rowModelId = convertRowIndexToModel( table.getSelectedRow() );
System.out.println("Removed item: "+String.valueOf(this.table.getSelectedRowCount()));
tableModel.removeRow(rowModelId);
}
You can learn more about view-indexes vs model-indexes from the Documentation on JTable introduction at the top. Some relevant quotes:
The JTable uses integers exclusively to refer to both the rows and the columns of the model that it displays. The JTable simply takes a tabular range of cells and uses getValueAt(int, int) to retrieve the values from the model during painting. It is important to remember that the column and row indexes returned by various JTable methods are in terms of the JTable (the view) and are not necessarily the same indexes used by the model.
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.
[...]The following shows how to convert coordinates from JTable to that of the underlying model:
int[] selection = table.getSelectedRows();
for (int i = 0; i < selection.length; i++) {
selection[i] = table.convertRowIndexToModel(selection[i]);
}
// selection is now in terms of the underlying TableModel
I gave an answer to a similar question a while back that explains this difference between view and model. That case dealt with improper indexing of columns rather than rows, but the issue is comparable.
Java JTable getting the data of the selected row
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html
You will find these methods in it:
getValueAt(int row, int column)
getSelectedRow()
getSelectedColumn()
Use a mix of these to achieve your result.
How to reliably get row index in JTable from MouseEvent?
Try this:
aJTable.rowAtPoint(evt.getPoint());
Related Topics
Why Is This Java Code in Curly Braces ({}) Outside of a Method
Which Loop Has Better Performance? Why
"Faceted Project Problem (Java Version Mismatch)" Error Message
Any Good Recommendations for Mp3/Sound Libraries for Java
Accessing Constructor of an Anonymous Class
Eclipse Memory Settings When Getting "Java Heap Space" and "Out of Memory"
Effect of a Bitwise Operator on a Boolean in Java
How to Convert Hex to Rgb Using Java
How to Disable the Default Console Handler, While Using the Java Logging API
Why Does Intellij Give Me "Package Doesn't Exist" Error
Where Is the Correct Location to Put Log4J.Properties in an Eclipse Project
How to Add a Timeout Value When Using Java's Runtime.Exec()
How to Achieve Conditional Resource Import in a Spring Xml Context
Trouble with Gson Serializing an Arraylist of Pojo'S