tgallei
tgallei

Reputation: 859

Change backgroundcolor of selected tab in JTabbedPane

I have a JTabbedPane with two "tabs". I want to try to give the selected tab a different color.
For this I use setBackgroundAt, but this does not change the GUI.
Could someone please tell me why this is so, or how I do it correctly?

public JTabbedPane getTabbedPane() {
    if (this.tabbedPane == null) {
        this.tabbedPane = new JTabbedPane();

        this.tabbedPane.addTab("Tab 1", new JPanel());
        this.tabbedPane.addTab("Tab 2", new JPanel());

        this.tabbedPane.addChangeListener(e -> {
            for(int i = 0; i < tabbedPane.getTabCount(); i++){
                tabbedPane.setBackgroundAt(i, Color.RED);
            }

            tabbedPane.setBackgroundAt(tabbedPane.getSelectedIndex(), Color.GREEN);
            tabbedPane.repaint();
        });
    }
    return this.tabbedPane;
}

The result looks like this:

Result

Upvotes: 0

Views: 926

Answers (1)

Sergiy Medvynskyy
Sergiy Medvynskyy

Reputation: 11327

JTabbedPane allows only to change the background of a non-selected tab. To change color of selected tab you must temporary replace "TabbedPane.selected" property of UIManager.

Example:

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;

/**
 * <code>TabbedPaneDemo</code>.
 */
public class TabbedPaneDemo {

    private JTabbedPane tabbedPane;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new TabbedPaneDemo()::startUp);
    }

    private void startUp() {
        JFrame frm = new JFrame("Tab demo");
        frm.add(getTabbedPane());
        frm.setSize(500, 200);
        frm.setLocationRelativeTo(null);
        frm.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        frm.setVisible(true);
    }

    private JTabbedPane getTabbedPane() {
        if (this.tabbedPane == null) {
            // UI hack - temporary replace selection color
            Color old = UIManager.getColor("TabbedPane.selected");
            UIManager.put("TabbedPane.selected", Color.GREEN);
            this.tabbedPane = new JTabbedPane();
            UIManager.put("TabbedPane.selected", old);

            this.tabbedPane.addTab("Tab 1", new JPanel());
            this.tabbedPane.addTab("Tab 2", new JPanel());
        }
        updateTabs();
        return this.tabbedPane;
    }

    private void updateTabs() {
        for (int i = 0; i < tabbedPane.getTabCount(); i++) {
            tabbedPane.setBackgroundAt(i, Color.RED);
        }
    }
}

This hack has one disadvantage: you cannot change the selection background anymore. So each selected tab in the tabbed pane will have green background.

Upvotes: 1

Related Questions