TITLE:JTabbedPaneのTabAreaをスクロール

Usage: #tags(tags)
Posted by at 2009-05-18

JTabbedPaneのTabAreaをスクロール

JTabbedPaneのTabAreaをJSlidterを使ってスクロールします。

  • &jnlp;
  • &jar;
  • &zip;
ScrollTabToVisible.png

サンプルコード

private static void scrollTabAt(JTabbedPane tp, int index) {
  JViewport vp = null;
  for(Component c:tp.getComponents()) {
    if("TabbedPane.scrollableViewport".equals(c.getName())) {
      vp = (JViewport)c;
      break;
    }
  }
  if(vp==null) return;
  final JViewport viewport = vp;
  for(int i=0;i<tp.getTabCount();i++)
    tp.setForegroundAt(i, i==index?Color.RED:Color.BLACK);
  Dimension d = tp.getSize();
  Rectangle r = tp.getBoundsAt(index);
  int gw = (d.width-r.width)/2;
  r.grow(gw, 0);
  viewport.scrollRectToVisible(r);
}
View in GitHub: Java, Kotlin

解説

JTabbedPane#setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT)としたJTabbedPaneのTabAreaは、名前が"TabbedPane.scrollableViewport"なJViewportに配置されています。 上記のサンプルでは、このJViewportを取得して、JViewport#scrollRectToVisible(Rectangle)メソッドを使用し、矢印ボタンをクリックせずにTabAreaのスクロールを行っています。

コメント