【问题标题】:Aligning icon to the left in JTabbedPane in Nimbus Look and Feel在 Nimbus 外观和感觉中的 JTabbedPane 中将图标向左对齐
【发布时间】:2013-11-16 05:14:12
【问题描述】:

我正在使用 Nimbus 外观和感觉创建一个带有 JTabbedPane 的应用程序

我已使用此代码放置标签:

pane.addTab("Welcome",new ImageIcon("resources\\1.png"),mainPanel,"Takes to the welcome page");

我希望图标出现在左侧并且

【问题讨论】:

  • 那么...你试过我的答案了吗?有用吗?请注意,此解决方案与 L&F 无关。
  • 是的。我没有将它应用于我的应用程序,但我尝试了你的代码并理解了这个概念。我喜欢带有关闭按钮的那个(类似于 google chrome 选项卡和其他选项卡式应用程序),是的,您的解决方案独立于外观,因为您将其对齐在面板内,然后添加它

标签: java swing user-interface jtabbedpane nimbus


【解决方案1】:

您可以通过JTabbedPane.setTabComponentAt(int index, Component component)方法设置自定义组件来呈现标签标题:

设置负责渲染标题的组件 指定标签。空值意味着JTabbedPane 将呈现标题 和/或指定选项卡的图标。非空值意味着 组件将呈现标题,JTabbedPane 不会呈现 标题和/或图标。

注意:组件不能是开发者已经拥有的组件 添加到选项卡式窗格中。

例如,您可以这样做:

JLabel label = new JLabel("Tab1");
label.setHorizontalTextPosition(JLabel.TRAILING); // Set the text position regarding its icon
label.setIcon(UIManager.getIcon("OptionPane.informationIcon"));

JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.LEFT);
tabbedPane.addTab(null, new JPanel());
tabbedPane.setTabComponentAt(0, label); // Here set the custom tab component

屏幕截图 1:


注意:使用此功能,您可以随意设置任何Component。例如,您可以使用 JButton 创建 JPanel 来关闭选项卡:

final JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.LEFT);

ActionListener actionListener = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        JButton button = (JButton)e.getSource();
        for(int i = 0; i < tabbedPane.getTabCount(); i++) {
            if(SwingUtilities.isDescendingFrom(button, tabbedPane.getTabComponentAt(i))) {
                tabbedPane.remove(i);
                break;
            }
        }
    }
};

JLabel label = new JLabel("Tab1", UIManager.getIcon("OptionPane.informationIcon"), JLabel.RIGHT);        
JButton closeButton = new JButton("X");
closeButton.addActionListener(actionListener);

JPanel tabComponent = new JPanel(new BorderLayout());
tabComponent.add(label, BorderLayout.WEST);
tabComponent.add(closeButton, BorderLayout.EAST);

tabbedPane.addTab(null, new JPanel());
tabbedPane.setTabComponentAt(0, tabComponent); // Here set the custom tab component

屏幕截图 2:


更新

您可能也想查看此主题:JTabbedPane: tab placement set to LEFT but icons are not aligned

【讨论】:

  • 选项卡组件居中(无论 JPanel 是如何构造的)。您知道如何在不重写 UI 的情况下使内部面板(选项卡组件)左对齐或右对齐吗?最佳解决方案是 LAF 安全的。
【解决方案2】:

有一个使用 HTML 格式的更简单的解决方案。 这是一个使用 html 代码格式化文本的示例,但您也可以格式化选项卡中的其他元素:

final String PRE_HTML = "<html><p style=\"text-align: left; width: 230px\">"; 
final String POST_HTML = "</p></html>"; 

tabbedpane.setTitleAt(0, PRE_HTML + "your title" + POST_HTML);
tabbedpane.setTitleAt(2, PRE_HTML + "your title 2" + POST_HTML);

【讨论】:

    猜你喜欢
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 2018-06-14
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    相关资源
    最近更新 更多