Name: rmT116609 Date: 05/19/2004
FULL PRODUCT VERSION :
java version "1.4.2_04"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_04-b05)
Java HotSpot(TM) Client VM (build 1.4.2_04-b05, mixed mode)
ADDITIONAL OS VERSION INFORMATION :
Microsoft Windows XP [Version 5.1.2600]
A DESCRIPTION OF THE PROBLEM :
JTable.getSelectedRow() returns 0 for empty table after "tabbing" into the table. The attached example shows this clearly.
STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Run the attached code and press TAB after the window shows. This will cause a valueChanged event on the table's row selection model. Inside this a message is printed if the following assertion fails:
table.getRowCount() == 0 && table.getSelectedRow() >= 0
EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
There should be nothing printed from the row selection listener.
ACTUAL -
The row selection listener does print a message indicating that the above assertion did indeed fail.
REPRODUCIBILITY :
This bug can be reproduced always.
---------- BEGIN SOURCE ----------
import javax.swing.*;
import javax.swing.event.*;
public class JTableBug {
public static void main(String[] args) {
JFrame frame = new JFrame("JTable Bug");
final JTable table = new JTable(new Object[][] {}, new String[] {"A","B"});
frame.getContentPane().add(new JScrollPane(table));
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) return;
final int rowCount = table.getRowCount();
final int selectedRow = table.getSelectedRow();
if (rowCount == 0 && selectedRow >= 0)
System.err.println("BUG: rowCount = " + rowCount + " selectedRow = " + selectedRow);
}
});
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.show();
}
}
---------- END SOURCE ----------
CUSTOMER SUBMITTED WORKAROUND :
Do not trust the method getSelectedRow() if getRowCount() == 0.
A possible workaround could be to subclass JTable and override getSelectedRow():
new JTable() {
public int getSelectedRow() {
return getRowCount() == 0 ? -1 : super.getSelectedRow();
}
};
(Incident Review ID: 270486)
======================================================================