JTabbedPaneの余白にJCheckBoxを配置
Total: 9921
, Today: 1
, Yesterday: 1
Posted by aterai at
Last-modified:
概要
JTabbedPane
の余白にJCheckBox
を配置して特定のタブの開閉を行います。
Screenshot

Advertisement
サンプルコード
class TabbedPaneWithCompBorder implements Border, MouseListener, SwingConstants {
private final JComponent dummy = new JPanel();
private final JCheckBox cbox;
private final JTabbedPane tab;
private Rectangle rect;
public TabbedPaneWithCompBorder(JCheckBox cbox, JTabbedPane tab) {
this.cbox = cbox;
this.tab = tab;
tab.addMouseListener(this);
cbox.setFocusPainted(false);
cbox.addMouseListener(new MouseAdapter() {
@Override public void mouseClicked(MouseEvent me) {
((AbstractButton) me.getComponent()).doClick();
}
});
}
@Override public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
Dimension size = cbox.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 = new Rectangle(xx, -2, size.width, size.height);
SwingUtilities.paintComponent(g, cbox, dummy, rect);
}
@Override public Insets getBorderInsets(Component c) {
return new Insets(0, 0, 0, 0);
}
@Override public boolean isBorderOpaque() {
return true;
}
private void dispatchEvent(MouseEvent me) {
if (rect == null || !rect.contains(me.getX(), me.getY())) {
return;
}
cbox.setBounds(rect);
cbox.dispatchEvent(SwingUtilities.convertMouseEvent(tab, me, cbox));
}
@Override public void mouseClicked(MouseEvent me) {
dispatchEvent(me);
}
@Override public void mouseEntered(MouseEvent me) {
dispatchEvent(me);
}
@Override public void mouseExited(MouseEvent me) {
dispatchEvent(me);
}
@Override public void mousePressed(MouseEvent me) {
dispatchEvent(me);
}
@Override public void mouseReleased(MouseEvent me) {
dispatchEvent(me);
}
}
View in GitHub: Java, Kotlin解説
JTabbedPane
のBorder
にSwingUtilities.paintComponent(...)
メソッドを使ってJCheckBox
を描画JCheckBox
がJTabbedPane
の子になってタブが増えないようにダミーパネルを中間コンテナに指定JTabbedPane
で受け取ったマウスイベントをSwingUtilities.convertMouseEvent(...)
メソッドを利用し、チェックボックス用に座標などを変換してイベント転送- タブとチェックボックスが重ならないようにフレームの最小サイズを設定
frame.setMinimumSize(new Dimension(240, 80));
- レイアウトマネージャーを利用して同様のことを行う方法もある
- Swing - Any layout suggestions for this?
- レイアウトマネージャーを自作するweebibさんの投稿 (reply 1)
OverlayLayout
を利用するcamickrさんの投稿 (reply 2)
- Swing - Any layout suggestions for this?