JTabbedPane:选项卡左侧的图标

9

你好,我正在使用Nimbus外观,并且有一个带有图标和文本的选项卡面板。 现在图标出现在文本的右侧,而我想把它放在左侧。

另外,我想在图标和文本之间添加一些间距。

谢谢!

1个回答

17

你需要自己设置选项卡组件,该组件控制选项卡标题的呈现方式。

// Create tabbed pane and add tabs.
JTabbedPane tabbedPane = ...

// Create bespoke component for rendering the tab.
JLabel lbl = new JLabel("Hello, World");
Icon icon = new ImageIcon(getClass().getResource("/foo/bar/hello.jpg"));
lbl.setIcon(icon);

// Add some spacing between text and icon, and position text to the RHS.
lbl.setIconTextGap(5);
lbl.setHorizontalTextPosition(SwingConstants.RIGHT);

// Assign bespoke tab component for first tab.
tabbedPane.setTabComponentAt(0, lbl);

显然,你可以将其封装在一个实用方法中:

private void addTab(JTabbedPane tabbedPane, Component tab, String title, Icon icon) {
  tabbedPane.add(tab);

  JLabel lbl = ... // Create bespoke label for rendering tab title.

  tabbedPane.setTabComponentAt(tabbedPane.getTabCount() - 1, lbl);
}

我之前使用了这段代码来向选项卡中添加组件、字符串、图标和工具提示:pane.addTab("选项卡名称", new ImageIcon("resources\1.png"), mainPanel," 工具提示文本");现在我想要实现相同的效果(即文本显示在右侧,图标显示在左侧),我尝试了您在上面评论中提到的方法,但是我的代码出现了异常,请帮忙解决。 - Gagan93
1
@Gagan93:请您将此作为另一个问题发布;如果我没有看到异常信息,我不确定我能提供帮助。 - Adamski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接