动态更改 JTabbedPane 活动选项卡颜色

Change JTabbedPane active tab color dynamically

我的要求是动态更改 JTabbedPane 的选项卡颜色。就像单击按钮时更改选项卡和选定的选项卡颜色一样。出于同样的原因,我不能使用 UIManager。但是标签颜色一旦设置和更改标签就无法正常工作。另外选择的选项卡总是显示默认颜色,而不是我设置的颜色。

代码如下:

import javax.swing.*;
import java.awt.*;

public class TestJTP extends JFrame {

    JTabbedPane tabbedPane;
    public TestJTP() {
        init();
    }

    private void init() {

        tabbedPane = new JTabbedPane();
        tabbedPane.addTab("Tab-1", null);
        tabbedPane.addTab("Tab-2", null);
        tabbedPane.addTab("Tab-3", null);
        tabbedPane.addTab("Tab-4", null);
        tabbedPane.addTab("Tab-5", null);

        JPanel panel = new JPanel();
        JButton b1 = new JButton("Orange,blue");
        b1.addActionListener(e -> {
            tabbedPane.setBackground(null);
            tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), null);
            tabbedPane.setBackground(Color.orange);
            tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), Color.blue);
        });
        JButton b2 = new JButton("Red,cyan");
        b2.addActionListener(e -> {
            tabbedPane.setBackground(null);
            tabbedPane.setBackground(Color.red);
            tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), null);
            tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), Color.cyan);
        });
        JButton b3 = new JButton("Green,magenta");
        b3.addActionListener(e -> {
            tabbedPane.setBackground(null);
            tabbedPane.setBackground(Color.green);
            tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), null);
            tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), Color.magenta);
        });
        panel.add(b1);
        panel.add(b2);
        panel.add(b3);
        getContentPane().add(panel, BorderLayout.NORTH);
        getContentPane().add(tabbedPane, BorderLayout.CENTER);
        pack();
        setVisible(true);
        setExtendedState(JFrame.MAXIMIZED_BOTH);
    }

    public static void main(String[] args) {
        new TestJTP();
    }
}

如果我明白你在问什么,试试:

//tabbedPane.setBackground(null);
tabbedPane.setBackground(Color.red);
//tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), null);
//tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), Color.cyan);
UIManager.put("TabbedPane.selected", Color.CYAN);
SwingUtilities.updateComponentTreeUI(tabbedPane);

这应该重置所有选项卡的默认“选项卡选择颜色”和“选项卡颜色”。