• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JLayerを使ってJTabbedPaneのタブの挿入位置を描画する
#navi(../)
RIGHT:Posted by [[aterai]] at 2012-01-23
*JLayerを使ってJTabbedPaneのタブの挿入位置を描画する [#t75e37f6]
JLayerを使って、タブのドラッグ&ドロップでの移動先をJTabbedPane上に描画します。

-&jnlp;
-&jar;
-&zip;

//#screenshot
#ref(https://lh3.googleusercontent.com/-xX0rzgauC5c/Txz4AxE_u2I/AAAAAAAABIM/jHQdxU1yP9g/s800/DnDLayerTabbedPane.png)

**サンプルコード [#d057781e]
#code{{
class DropLocationLayerUI extends LayerUI<DnDTabbedPane> {
  private static final int LINEWIDTH = 3;
  private final Rectangle lineRect = new Rectangle();
  @Override public void paint(Graphics g, JComponent c) {
    super.paint (g, c);
    JLayer layer = (JLayer)c;
    DnDTabbedPane tabbedPane = (DnDTabbedPane)layer.getView();
    DnDTabbedPane.DropLocation loc = tabbedPane.getDropLocation();
    if(loc != null && loc.isDropable() && loc.getIndex()>=0) {
      int index = loc.getIndex();
      boolean isZero = index==0;
      Rectangle r = tabbedPane.getBoundsAt(isZero?0:index-1);
      if(tabbedPane.getTabPlacement()==JTabbedPane.TOP ||
         tabbedPane.getTabPlacement()==JTabbedPane.BOTTOM) {
        lineRect.setRect(
            r.x-LINEWIDTH/2+r.width*(isZero?0:1), r.y,LINEWIDTH,r.height);
      }else{
        lineRect.setRect(
            r.x,r.y-LINEWIDTH/2+r.height*(isZero?0:1), r.width,LINEWIDTH);
      }
      Graphics2D g2 = (Graphics2D)g.create();
      g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
      g2.setColor(Color.RED);
      g2.fill(lineRect);
      g2.dispose();
    }
  }
}
}}

**解説 [#se007f95]
上記のサンプルでは、[[JTabbedPaneのタブをドラッグ&ドロップ>Swing/DnDTabbedPane]]や、[[JTabbedPane間でタブのドラッグ&ドロップ移動>Swing/DnDExportTabbedPane]]のようにGlassPaneを使用する代わりに、JDK 1.7.0 で導入されたJLayerを使用して、タブの挿入先を描画しています。JLayerを使用することで、別ウィンドウにあるJTabbedPaneへのタブ移動などの描画が簡単にできるようになっています。

- Debug: Lightweight
-- ドラッグ中の半透明タブイメージは、JDK1.7.0で導入された、TransferHandler#setDragImage(...)メソッドを使用して描画
-- ウインドウの外では半透明タブイメージは非表示
- Debug: Heavyweight
-- ドラッグ中の半透明タブイメージは、半透明のJWindowにJLabelを追加して表示
-- ウインドウの外でも半透明タブイメージが表示可能
-- 表示位置のオフセットが(0, 0)の場合、ドラッグイベントが元のJFrameに伝わらない?

#code{{
private final JLabel label = new JLabel();
private final JWindow dialog = new JWindow();
public TabTransferHandler() {
  dialog.add(label);
  //dialog.setAlwaysOnTop(true);
  dialog.setOpacity(0.5f);
  //com.sun.awt.AWTUtilities.setWindowOpacity(dialog, 0.5f); // JDK 1.6.0
  DragSource.getDefaultDragSource().addDragSourceMotionListener(
      new DragSourceMotionListener() {
    @Override public void dragMouseMoved(DragSourceDragEvent dsde) {
      Point pt = dsde.getLocation();
      pt.translate(5, 5);
      dialog.setLocation(pt);
    }
  });
//...
}}

**参考リンク [#t09438dd]
- [[JTabbedPaneのタブをドラッグ&ドロップ>Swing/DnDTabbedPane]]
- [[JTabbedPane間でタブのドラッグ&ドロップ移動>Swing/DnDExportTabbedPane]]

**コメント [#b93fe731]
#comment