This discussion is archived
2 Replies Latest reply: Oct 8, 2004 8:32 PM by camickr RSS

scroll Jtable

807587 Newbie
Currently Being Moderated
I have a JTable inside a JScrollPane and want to set the focus to edit the last line of the table
by API.
OK, I use getEditableComponent() to set the focus but I can't get the scroiling to maximum value.
It is however possible to do it setting the value of the verticalsrollbar to the maximum value but the JTable runs into some ugly displaying problems. There must be a way to get the viewport scrolled so that the editing component is visible

any hints?
  • 1. Re: scroll Jtable
    807587 Newbie
    Currently Being Moderated
    Perhaps you've tried JViewport's scrollRectToVisible -- that doesn't work well for me.... but it's setViewPosition
    does:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    
    public class TableExample {
        public static void main(String[] args) {
            final int ROWS = 100;
            final JTable table = new JTable(ROWS, 6);
            for(int i=0; i<ROWS; ++i)
                table.setValueAt(new Integer(i), i, 0);
            final JScrollPane sp = new JScrollPane(table);
            JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, ROWS-1, 1));
            spinner.addChangeListener(new ChangeListener(){
                public void stateChanged(ChangeEvent e) {
                    JSpinner spin = (JSpinner) e.getSource();
                    int row = ((Number)spin.getValue()).intValue();
                    Rectangle bounds = table.getCellRect(row,0,true);
                    //sp.getViewport().scrollRectToVisible(bounds);
                    sp.getViewport().setViewPosition(bounds.getLocation());
                }
            });
    
            JPanel south = new JPanel();
            south.add(new JLabel("Make sure this row is visible: "));
            south.add(spinner);
            JFrame frame = new JFrame("TableExample");
            Container cp = frame.getContentPane();
            cp.add(sp, BorderLayout.CENTER);
            cp.add(south, BorderLayout.SOUTH);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    }
  • 2. Re: scroll Jtable
    camickr Expert
    Currently Being Moderated
    There must be a way to get the viewport scrolled so that the editing component is visible
    table.changeSelection(....);