views:

228

answers:

2

I have a jtable inside of a scrollpane. how can i stop the scrollpane from scrolling up or down when a cell that is partly out of view gains focus?

the problem is i am setting the cells to editable when the user mouses over them, so when you mouse over a cell that's partly out of view, the view changes suddenly. I don't like this behaviour. any ideas on how to change it?

A: 

You could try calling "setAutoscrolls(false)" on your table.

Although the javadoc talks about handing mouse drag events, it should also disable scrolling on row/cell sections also.

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class TableTest extends JFrame {

    private JTable table;
    /**
     * Create a new TableTest Frame.
     * @param title The title of the frame.
     */
    public TableTest() {

        Object[][] tableData = new Object[][] {
                {1, "One"}, {2, "Two"}, {3, "Three"},
                {4, "Four"}, {5, "Five"}, {6, "Six"}};

        DefaultTableModel tableModel = new DefaultTableModel(tableData, new String[] {"A", "B"});
        table = new JTable(tableModel);
        table.setAutoscrolls(false);

        JScrollPane scrolly = new JScrollPane(table);
        setLayout(new BorderLayout());
        add(scrolly, BorderLayout.CENTER);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        TableTest frame = new TableTest();
        frame.pack();
        frame.setSize(200, 100);
        frame.setVisible(true);
    }
}
Aaron
i've tried the suggested method on both the scrollpane and the jtable and neither change the behavior i described.
Victor
Strange. Unless I've misunderstood what you are trying to do it definately worked for me. I've posted the example code I used to test this.You should get different behaviour when the setAutoscrolls(false) call is removed/added.
Aaron
A: 

Took me hours of searching but I got it to work for me.

Override this method with your JTable subclass

public void scrollRectToVisible(java.awt.Rectangle aRect) { if(getAutoscrolls()) super.scrollRectToVisible(aRect); }

Now table.setAutoscrolls(false) should work properly.

Seth