Under both JDK1.2 and JDK1.1.7+Swing1.1 on both Solaris and Window NT, the row
selection is not reliably rendered when it is called from code. Sometime the
selected row is not highlighted and sometime the previously selected row is not
cleared. I included test code below to illustrate the problem.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TestTable extends JPanel implements ActionListener {
private Model model;
private JTable table;
private JScrollPane scrollPane;
private JButton btest;
private Random rand;
private int size = 50;
public TestTable() {
rand = new Random();
model = new Model();
table = new JTable(model);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(500, 200));
btest = new JButton("Scroll and Select");
btest.addActionListener(this);
setLayout(new BorderLayout());
add("Center", scrollPane);
add("South", btest);
}
public void actionPerformed(ActionEvent evt) {
JButton b = (JButton)evt.getSource();
if (b == btest) {
int select = (int)(size * rand.nextFloat());
table.setRowSelectionInterval(select, select);
JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
scrollBar.setValue(select * scrollBar.getMaximum() / size);
System.out.println("select row " + select);
}
}
class Model extends AbstractTableModel {
final String[] columnNames = {"0", "1", "2", "3", "4",
"5", "6", "7", "8", "9"};
public Model () {
}
public void updateTable() {
fireTableDataChanged();
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return size;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return new Integer(row * col);
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Test TestTable");
TestTable p = new TestTable();
f.getContentPane().add("Center", p);
f.pack();
f.setVisible(true);
}
}