How to scroll JList to bottom
I have a JList on a JScrollPane, and it updates in real-time.
As the data fills the pane, I want it to scroll to the bottom all the time,
but it stays at the top. I update as follows:
String voltString[]=new String[someNumber];
// Set the strings to stuff--code omitted
//...
voltList.setListData(voltStrings);
voltList.ensureIndexIsVisible(voltStrings.length);
But it doesn't work.The API for ensureIndexIsVisible says something
about a JViewPort, but I am not sure what it means--I have it on a
JScrollPane, not a JViewPort.
works OK like this
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Testing extends JFrame
{
int counter = 0;
javax.swing.Timer timer;
public Testing()
{
setLocation(200,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
final DefaultListModel lm = new DefaultListModel();
final JList list = new JList(lm);
JScrollPane sp = new JScrollPane(list);
sp.setPreferredSize(new Dimension(100,150));
getContentPane().add(sp);
pack();
setVisible(true);
ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent ae){
lm.addElement(counter);
counter++;
list.ensureIndexIsVisible(lm.size()-1);
if(counter > 100) timer.stop();}};
timer = new javax.swing.Timer(100,al);
timer.start();
}
public static void main(String[] args){new Testing();}
}
I think the problem is that I used size() for the index, and
you used size()-1, which makes since, because the
size()th element does not exist.
So it works now, but it shows the second to last element,
with the last element not quite showing up. Strange, but
better than it was.
Thanks,
Chuck.