我正在使用Nimbus外观创建一个带有JTabbedPane
的应用程序。
我使用了以下代码来放置标签页:
pane.addTab("Welcome",new ImageIcon("resources\\1.png"),mainPanel,"Takes to the welcome page");
我希望图标出现在左边。
我正在使用Nimbus外观创建一个带有JTabbedPane
的应用程序。
我使用了以下代码来放置标签页:
pane.addTab("Welcome",new ImageIcon("resources\\1.png"),mainPanel,"Takes to the welcome page");
设置负责呈现指定选项卡的标题的组件。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:
注意:使用此功能,您可以将任何组件
设置为所需状态。例如,您可以制作一个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:将选项卡放置于左侧,但图标未对齐
有一个更简单的解决方案,使用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);