---
category: swing
folder: TabbedPaneWithCheckBox
title: JTabbedPaneの余白にJCheckBoxを配置
tags: [JTabbedPane, JCheckBox, Border]
author: aterai
pubdate: 2006-04-03T01:35:12+09:00
description: JTabbedPaneの余白にJCheckBoxを配置して特定のタブの開閉を行います。
image: https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTUQ8ALIWI/AAAAAAAAAlw/7jfCbNrxWK8/s800/TabbedPaneWithCheckBox.png
---
* Summary [#summary]
`JTabbedPane`の余白に`JCheckBox`を配置して特定のタブの表示・非表示を切り替えます。
#download(https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTUQ8ALIWI/AAAAAAAAAlw/7jfCbNrxWK8/s800/TabbedPaneWithCheckBox.png)
* Source Code Examples [#sourcecode]
#code(link){{
class TabbedPaneWithCompBorder
implements Border, MouseListener, SwingConstants {
private final JCheckBox checkBox;
private final JTabbedPane tab;
private final Container rubberStamp = new JPanel();
private final Rectangle rect = new Rectangle();
protected TabbedPaneWithCompBorder(JCheckBox checkBox, JTabbedPane tab) {
this.checkBox = checkBox;
this.tab = tab;
}
@Override public void paintBorder(
Component c, Graphics g, int x, int y, int width, int height) {
Dimension size = checkBox.getPreferredSize();
int xx = tab.getSize().width - size.width;
Rectangle lastTab = tab.getBoundsAt(tab.getTabCount() - 1);
int tabEnd = lastTab.x + lastTab.width;
if (xx < tabEnd) {
xx = tabEnd;
}
rect.setBounds(xx, -2, size.width, size.height);
SwingUtilities.paintComponent(g, checkBox, rubberStamp, rect);
}
@Override public Insets getBorderInsets(Component c) {
return new Insets(0, 0, 0, 0);
}
@Override public boolean isBorderOpaque() {
return true;
}
private void dispatchEvent(MouseEvent e) {
if (!rect.contains(e.getX(), e.getY())) {
return;
}
checkBox.setBounds(rect);
checkBox.dispatchEvent(SwingUtilities.convertMouseEvent(tab, e, checkBox));
}
@Override public void mouseClicked(MouseEvent e) {
dispatchEvent(e);
}
@Override public void mouseEntered(MouseEvent e) {
dispatchEvent(e);
}
@Override public void mouseExited(MouseEvent e) {
dispatchEvent(e);
}
@Override public void mousePressed(MouseEvent e) {
dispatchEvent(e);
}
@Override public void mouseReleased(MouseEvent e) {
dispatchEvent(e);
}
}
}}
* Description [#explanation]
* Description [#description]
- `JTabbedPane`の`Border`に`SwingUtilities.paintComponent(...)`メソッドを使って`JCheckBox`を描画
- `JCheckBox`が`JTabbedPane`の子になってタブが増えないように、別途レンダリング用`JPanel`を作成して中間コンテナに指定
- `JTabbedPane`で受け取ったマウスイベントを`SwingUtilities.convertMouseEvent(...)`メソッドを利用し、`JCheckBox`用に座標などを変換してイベント転送
- タブと`JCheckBox`が重ならないように親`JFrame`の最小サイズを設定
#code{{
frame.setMinimumSize(new Dimension(240, 80));
}}
----
- レイアウトマネージャーを利用して同様のことを行う方法もある
-- [https://community.oracle.com/thread/1389350 Swing - Any layout suggestions for this?]
--- レイアウトマネージャーを自作するweebibさんの投稿 (reply 1)
--- `OverlayLayout`を利用するcamickrさんの投稿 (reply 2)
* Reference [#reference]
- [[JTabbedPaneの余白に文字列を表示>Swing/TabbedPaneWithText]]
- [[JTabbedPaneの余白にJButtonを配置>Swing/TabbedPaneWithButton]]
* Comment [#comment]
#comment
#comment