向其中添加选项卡时,JTabbedPane可以定义选项卡的图标。在选项卡的启用或禁用状态下,该图标将显示在选项卡标题旁边。为了使用户界面更好,您还可以为选项卡定义禁用的图标。当标签的状态无效,将显示此图标。
要为标签分配禁用的图标,请使用JTabbedPane的setDisabledIconAt(int index, Icon icon)方法。与往常一样,index参数从零开始,这意味着第一个选项卡位于index number处0。该icon参数是选项卡的禁用图标。
package org.nhooo.example.swing; import javax.swing.*; import java.awt.*; public class TabbedPaneDisableIcon extends JPanel { private ImageIcon[] disableIcons = { new ImageIcon(this.getClass().getResource("/images/test-pass-icon-disable.png")), new ImageIcon(this.getClass().getResource("/images/test-fail-icon-disable.png")), new ImageIcon(this.getClass().getResource("/images/test-error-icon-disable.png")), }; public TabbedPaneDisableIcon() { initializeUI(); } private void initializeUI() { this.setLayout(new BorderLayout()); this.setPreferredSize(new Dimension(500, 200)); JTabbedPane pane = new JTabbedPane(); ImageIcon tab1Icon = new ImageIcon(this.getClass().getResource("/images/test-pass-icon.png")); ImageIcon tab2Icon = new ImageIcon(this.getClass().getResource("/images/test-fail-icon.png")); ImageIcon tab3Icon = new ImageIcon(this.getClass().getResource("/images/test-error-icon.png")); JPanel content1 = new JPanel(); JPanel content2 = new JPanel(); JPanel content3 = new JPanel(); pane.addTab("Success", tab1Icon, content1); pane.addTab("Fail", tab2Icon, content2); pane.addTab("Error", tab3Icon, content3); for (int i = 0; i < pane.getTabCount(); i++) { pane.setDisabledIconAt(i, disableIcons[i]); } // 禁用最后一个选项卡以查看显示的禁用图标。 pane.setEnabledAt(pane.getTabCount() - 1, false); this.add(pane, BorderLayout.CENTER); } public static void showFrame() { JPanel panel = new TabbedPaneDisableIcon(); panel.setOpaque(true); JFrame frame = new JFrame("JTabbedPane Demo"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setContentPane(panel); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { TabbedPaneDisableIcon.showFrame(); } }); } }