/* $Id$ */
/* Copyright 2010 Sebastian Haufe
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
[url]http://www.apache.org/licenses/LICENSE-2.0[/url]
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package com.ebenius;
import java.awt.BorderLayout;
import java.util.List;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
public class TableScrollTest {
/**
* Test main method.
*
* @param args ignored
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
static void createAndShowGUI() {
final DefaultTableModel model = new DefaultTableModel(0, 2);
final JTable table = new JTable(model);
// create a row per 200 ms
final SwingWorker<Void, Integer> sw = new SwingWorker<Void, Integer>() {
@SuppressWarnings("boxing")
@Override
protected Void doInBackground() throws Exception {
for (int i = 0; i < 1000; i++) {
Thread.sleep(200);
publish(i);
}
return null;
}
@Override
protected void process(List<Integer> chunks) {
for (int i : chunks) {
model.addRow(new Object[] { "", "" });
}
}
};
sw.execute();
// scroll the table on insert
model.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
if (e.getType() == TableModelEvent.INSERT) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
table.scrollRectToVisible(table.getCellRect(
table.getRowCount() - 1, 0, true));
}
});
}
}
});
// build and show the test GUI
final JPanel contentPane = new JPanel(new BorderLayout(6, 6));
contentPane.add(new JScrollPane(table));
final JFrame f = new JFrame("Test Frame: TableScrollTest"); //$NON-NLS-1$
f.setContentPane(contentPane);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setVisible(true);
}
}