TITLE:JTabbedPaneの余白にJButtonを配置

Posted by terai at 2008-03-03

JTabbedPaneの余白にJButtonを配置

JTabbedPaneのタブエリアに余白を作成し、そこにOverlayLayoutを使ってJButtonを配置します。

  • &jnlp;
  • &jar;
  • &zip;

#screenshot

サンプルコード

JPanel p = new JPanel();
p.setLayout(new OverlayLayout(p));
button.setAlignmentX(0.0f);
button.setAlignmentY(0.0f);
tabPane.setAlignmentX(0.0f);
tabPane.setAlignmentY(0.0f);
p.add(button);
p.add(tabPane);
public InsetsUIResource getButtonPaddingTabAreaInsets(JButton b) {
  int bw = b.getPreferredSize().width;
  int bh = b.getPreferredSize().height;
  Insets insets = UIManager.getInsets("TabbedPane.tabInsets");
  Insets ti = (insets!=null)?insets:new Insets(0,0,0,0);
  insets = UIManager.getInsets("TabbedPane.tabAreaInsets");
  Insets ai = (insets!=null)?insets:new Insets(0,0,0,0);
  FontMetrics metrics = getFontMetrics(getFont());
  int tih = bh - metrics.getHeight()-ti.top-ti.bottom-ai.bottom;
  return new InsetsUIResource(Math.max(ai.top, tih), bw+ai.left, ai.bottom, ai.right);
}

解説

上記のサンプルは、以下のような動作*1の仕様になっています。

  • タブエリアの左上にあるボタンをクリックするとタブが追加される
  • メニューからすべてのタブを削除する
  • タブエリアに余裕がある場合は80pt、無い場合は(タブエリアの幅/タブ数)と、常にタブ幅は一定
    • 折り返しや、スクロールが発生するとレイアウトが崩れるため

コンポーネントの追加には、以下の方法を使用しています(比較:JTabbedPaneの余白にJCheckBoxを配置)。

  • ボタンの幅だけ、tabAreaInsets の左余白を拡大する
  • OverlayLayout で、JButtonとJTabbedPane(上で作った余白に)を重ねて表示
    • このため、JTabbedPane.TOP にしか対応していない

参考リンク

コメント