• 追加された行はこの色です。
  • 削除された行はこの色です。
---
title: JTabbedPaneのTabAreaをスクロール
tags: [JTabbedPane, JViewport, JSlider]
author: aterai
pubdate: 2009-05-18T14:51:20+09:00
description: JTabbedPaneのTabAreaをJSliderを使ってスクロールします。
---
* 概要 [#wacc0838]
* 概要 [#summary]
`JTabbedPane`の`TabArea`を`JSlider`を使ってスクロールします。

#download(https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTSn6mtDdI/AAAAAAAAAjE/ja_v92IXLsU/s800/ScrollTabToVisible.png)

* サンプルコード [#d4ebe884]
* サンプルコード [#sourcecode]
#code(link){{
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;
  for (Component c: tp.getComponents()) {
    if ("TabbedPane.scrollableViewport".equals(c.getName())) {
      vp = (JViewport) c;
      break;
    }
  }
  if(vp==null) return;
  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);
  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;
  int gw = (d.width - r.width) / 2;
  r.grow(gw, 0);
  viewport.scrollRectToVisible(r);
}
}}

* 解説 [#u1995ea4]
* 解説 [#explanation]
`JTabbedPane#setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT)`とした`JTabbedPane`の`TabArea`は、名前が`TabbedPane.scrollableViewport`な`JViewport`に配置されています。

上記のサンプルでは、この`JViewport`を取得して、`JViewport#scrollRectToVisible(Rectangle)`メソッドを使用し、矢印ボタンをクリックせずに`TabArea`のスクロールを行っています。

//* 参考リンク
* コメント [#zf0217a0]
//* 参考リンク [#reference]
* コメント [#comment]
#comment
#comment