Home > OS >  Change JTabbedPane active tab color dynamically
Change JTabbedPane active tab color dynamically

Time:10-10

My requirement is to change tabs colos of JTabbedPane dynamically. Like change of tabs and selected tabs colors on button click. For the same reason I cannot use UIManager. But tabs color once set and changing tab is not working properly. Also selected tab is always showing default color and not the one I set.

Below is the code:

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();
    }
}

CodePudding user response:

If I understand what you are asking try:

//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);

This should reset the default "tab selection color" and the "tab color" for all tabs.

  • Related