JScrollPane不响应scrollRectToVisible

时间:2014-11-05 14:17:36

标签: java swing jscrollpane

我有以下窗口:

public class MyWindows extends JFrame {


private final JScrollPane pane;

public MyWindows(){
    super();

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Container cp = getContentPane();
    cp.setLayout(new BorderLayout());

    JPanel panel = new JPanel();
    pane = new JScrollPane(panel);
    pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);


    JButton left = new JButton("<");
    left.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            moveLeft();
        }
    });
    cp.add(left, BorderLayout.WEST);


    panel.setLayout(new GridLayout(1,0));
    for(int i = 1; i<20; i++) {
        panel.add(new JButton("hallo nummer "+i));
    }



    cp.add(pane, BorderLayout.CENTER);


    JButton right = new JButton(">");
    cp.add(right, BorderLayout.EAST);

    this.setLocationRelativeTo(null);



    pack();


    this.setSize(300, 100);

}

private void moveLeft() {
    Rectangle rec = pane.getVisibleRect();
    rec.setLocation((int)(rec.getX()+1000), (int)rec.getY());
    System.out.println(rec);
    pane.scrollRectToVisible(rec);
    System.out.println(pane.getVisibleRect());
}

}

Screenshot of window

我的想法是使用左侧和右侧的按钮沿中心的按钮滚动。

不幸的是,moveLeft() - Method在滚动时完全没有任何意义。

目标矩形是java.awt.Rectangle [x = 1000,y = 0,width = 202,height = 61]

对我来说,看起来像ScrollPane应该能够滚动到的矩形。

我错过了什么?

另外,对于代码墙感到抱歉,但我不知道错误可能在哪里。

1 个答案:

答案 0 :(得分:3)

在所需组件(在您的案例中为scrollRectToVisible)上调用JPanel方法,但在JScrollPane对象上。

private JPanel panel;

...

private void moveLeft() {
    Rectangle rec = panel.getVisibleRect();
    rec.setLocation((int) (rec.getX() + 1000), (int) rec.getY());
    System.out.println(rec);
    panel.scrollRectToVisible(rec);
    System.out.println(panel.getVisibleRect());
}