Swing/TabbedPaneWithText のバックアップの現在との差分(No.15)
- category: swing folder: TabbedPaneWithText title: JTabbedPaneの余白に文字列を表示 tags: [JTabbedPane, FontMetrics, JLayer] author: aterai pubdate: 2005-12-26T12:36:53+09:00 description: JTabbedPaneの右側の余白に文字列を表示します。 description: JTabbedPaneのタブエリア右側の余白に文字列を表示します。 image:
概要
JTabbedPane
の右側の余白に文字列を表示します。Swing - JTabbedPane with non-tabbed textの投稿からソースコードを引用しています。
JTabbedPane
のタブエリア右側の余白に文字列を表示します。
Screenshot
Advertisement
サンプルコード
tab = new JTabbedPane() {
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
String text = "←ちょっとしたタブの説明など";
FontMetrics fm = getFontMetrics(getFont());
int stringWidth = fm.stringWidth(text) + 10;
int x = getSize().width - stringWidth;
Rectangle lastTab = getUI().getTabBounds(this, getTabCount() - 1);
Rectangle lastTab = getBoundsAt(getTabCount() - 1);
int tabEnd = lastTab.x + lastTab.width;
if (x < tabEnd) {
x = tabEnd;
}
g.drawString(text, x + 5, 18);
}
};
View in GitHub: Java, Kotlin解説
JTabbedPane#paintComponent
メソッドをオーバーライドして、タブコンポーネントの右側の余白に文字列を描画しています。
JTabbedPane#paintComponent(...)
メソッドをオーバーライドして、タブコンポーネントの右側の余白に文字列を描画しています。
右端に十分な余白が無く、文字列を描画するとタブ上に重なってしまう場合は、最後のタブの横から文字列を描画するようになっています。
右端に十分な余白が無く文字列を描画するとタブ上に重なってしまう場合は、最後のタブの横から文字列を描画するようになっています。
JDK 1.7.0
のJLayer
を使用する場合は、以下のような方法があります。
-
JDK 1.7.0
以降の場合JLayer
を使用してラベルを描画する方法もある
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.*;
public class TopRightCornerLabelLayerUITest {
public static JComponent makeUI() {
JTabbedPane tab = new JTabbedPane();
tab.addTab("New tab1", new JLabel("1"));
tab.addTab("New Tab2", new JLabel("2"));
JTabbedPane tabs = new JTabbedPane();
tabs.addTab("New tab1", new JLabel("1"));
tabs.addTab("New Tab2", new JLabel("2"));
JPanel p = new JPanel(new BorderLayout());
p.add(new JLayer<JComponent>(tab, new TopRightCornerLabelLayerUI()));
p.add(new JLayer<JComponent>(tabs, new TopRightCornerLabelLayerUI()));
return p;
}
#spanadd
#spanend
private static void createAndShowUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
#spanadd
#spanend
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowUI();
}
});
}
}
#spanadd
#spanend
class TopRightCornerLabelLayerUI extends LayerUI<JComponent> {
private JLabel l = new JLabel("A Label at right corner");
private JPanel rubberStamp = new JPanel();
@Override public void paint(Graphics g, JComponent c) {
super.paint(g, c);
Dimension d = l.getPreferredSize();
int x = c.getWidth() - d.width - 5;
SwingUtilities.paintComponent(g, l, rubberStamp, x, 2, d.width, d.height);
}
}
参考リンク
- Swing - JTabbedPane with non-tabbed text
- JTabbedPaneの余白にJCheckBoxを配置
- JTabbedPaneの余白にJButtonを配置
-
JLabel
ではなくクリック可能なJButton
をJTabbedPane
に配置するサンプル
-