简体   繁体   English

如何改变JTabbedPane的背景颜色?

[英]How to change background color of JTabbedPane?

I know you can modify the LaF properties , but how do you accomplish this without doing such? 我知道您可以修改LaF属性 ,但是如何在不执行此操作的情况下完成此操作? I only ask because setBackground doesn't seem to do it. 我只是问,因为setBackground似乎没有这样做。

Note that I'm looking to change the following properties: 请注意,我正在寻找更改以下属性:

  1. TabbedPane.background (or TabbedPane.contentAreaColor ?) TabbedPane.background (或TabbedPane.contentAreaColor ?)
  2. TabbedPane.tabAreaBackground

Using TabComponentsDemo as an example, setBackgroundAt() seems to work: 使用TabComponentsDemo作为示例, setBackgroundAt()似乎工作:

private void initTabComponent(int i) {
    pane.setTabComponentAt(i, new ButtonTabComponent(pane));
    pane.setBackgroundAt(i, Color.getHSBColor((float)i/tabNumber, 1, 1));
}

Addendum: As @camickr helpfully observed, the target component must be opaque . 附录:正如@camickr所见,目标组件必须是不透明的

TabColors

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

/** @see http://stackoverflow.com/questions/8752037 */
public class TabColors extends JPanel {

    private static final int MAX = 5;
    private final JTabbedPane pane = new JTabbedPane();

    public TabColors() {
        for (int i = 0; i < MAX; i++) {
            Color color = Color.getHSBColor((float) i / MAX, 1, 1);
            pane.add("Tab " + String.valueOf(i), new TabContent(i, color));
            pane.setBackgroundAt(i, color);
        }
        this.add(pane);
    }

    private static class TabContent extends JPanel {

        private TabContent(int i, Color color) {
            setOpaque(true);
            setBackground(color);
            add(new JLabel("Tab content " + String.valueOf(i)));
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(320, 240);
        }
    }

    private void display() {
        JFrame f = new JFrame("TabColors");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TabColors().display();
            }
        });
    }
}

You can also do the following: 您还可以执行以下操作:

for (int i = 0; i < this.getTabCount(); i++) {
    this.getComponentAt(i).setBackground(Color.DARK_GRAY);
}

or 要么

for (int i = 0; i < this.getTabCount(); i++) {
            this.setBackgroundAt(i, Color.DARK_GRAY);
            this.getComponentAt(i).setBackground(Color.DARK_GRAY);
}

for tab and panel backgrounds 用于标签和面板背景

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM