使用scrollRectToVisible()时,需要调用两次才能正确修复位置。怎么修?

时间:2013-12-30 08:44:10

标签: java swing scroll jpanel jscrollpane

我的情况是:我的项目中有2个选项卡视图,选项卡A视图显示列表和选项卡B显示JScrollPane中的图表。 功能是:单击选项卡A中的一个列表项,它将转到选项卡B并滚动到指向的图表X(可能是第一个,或第二个....)

问题是:如果单击选项卡A中的一个项目,选项卡B视图将滚动到最后一个图表(位于JScrollPane的底部)。然后转到选项卡A,单击另一个项目,选项卡B 滚动到第一个图表(位于JScrollPane顶部)。 但是,JScrollPane仍然固定在底部。 但是,如果我转到标签A并单击相同的项目 agian ,标签B可以正确滚动到第一个图表。

代码如下:

  

protected void buildUI()      {          setLayout(new BorderLayout());

   myChartPanel = new JPanel( new GridBagLayout() );

   // add different charts for different Item in Tab A
   myChartPanel.add(..) 

   myGraphViewPane = new JScrollPane();
   Border scrollPaneBorder = myGraphViewPane.getBorder();
   myGraphViewPane.setBorder( null );

   //Set single graph view visible by default
   myGraphViewPane.setViewportView( myChartPanel );

   add( myGraphViewPane, BorderLayout.CENTER );
   setBorder( scrollPaneBorder );
     

}

我在下面尝试过滚动码,但都没有效果:

  

myChartPanel.scrollRectToVisible(focusChart.getBounds());

  

myGraphViewPane.getVerticalScrollBar()。setValue(focusChart.getLocation()。x);

  

myGraphViewPane.getViewport()。setViewPosition(new Point(focusChart.getLocation()。x,chartView.getLocation()。y));

为什么只点击两次,它可以滚动到正确的位置?太奇怪了!

1 个答案:

答案 0 :(得分:5)

尝试将myChartPanel.scrollRectToVisible( focusChart.getBounds() );电话打包在SwingUtilities.invokeLater()

相关问题