在Nimbus外观中将图标左对齐在JTabbedPane中

5

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

我使用了以下代码来放置标签页:

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

我希望图标出现在左边。

应用程序的截图


1
那么...你试过我的答案了吗?有用吗?请注意,这个解决方案与外观和感觉无关。 - dic19
1
嗯,我没有将它应用到我的应用程序中,但是我尝试了你的代码并理解了概念。我喜欢带有关闭按钮的那个(类似于 Google Chrome 标签和其他标签式应用程序),而且你的解决方案是独立于外观和感觉的,因为你将它对齐在一个面板内然后添加。 - Gagan93
2个回答

10
您可以通过JTabbedPane.setTabComponentAt(int index, Component component)方法设置自定义组件来渲染选项卡标题:

设置负责呈现指定选项卡的标题的组件。null值意味着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:

enter image description here


注意:使用此功能,您可以将任何组件设置为所需状态。例如,您可以制作一个JPanel与一个用于关闭选项卡的JButton

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:将选项卡放置于左侧,但图标未对齐


选项卡组件是居中对齐的(无论 JPanel 如何构建)。您知道如何在不重写用户界面的情况下使内部面板(选项卡组件)左对齐或右对齐的方法吗?最好的解决方案是 LAF 安全的。 - Zbigniew

0

有一个更简单的解决方案,使用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);

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