设置面板的backgroundColor在JTabbedPane之外工作但不在内部工作

时间:2015-10-16 02:20:24

标签: java swing background jtabbedpane

我遇到的问题是,当我的JTabbedPane内部没有设置(或没有显示)内部面板的背景颜色

我有以下结构:

JPanel BorderLayout:
   JTabbedPane (BorderLayout.Center):
      JPanel Default
      ..

当我将内部JPanel添加到BorderLayout.CENTER而不是JTabbedPane的borderLayout时,我可以看到背景颜色,但是如果我的内部面板位于选项卡式窗格中,并且选项卡式窗格被添加到中心,则背景颜色是默认的,似乎是覆盖它。

panel1.setBackground(Color.WHITE);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add(panel1);

//add tabbed pane to panel with borderlayout
//Background color of this panel is also set previously
add(tabbedPane, BorderLayout.CENTER);

1 个答案:

答案 0 :(得分:1)

如何制作所需的组件透明

package javaapplication31;

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

import java.awt.Dimension;


public class JavaApplication31
{
    public static void main(String[] args)
    {
        Runnable r = new Runnable()
        {
            @Override
            public void run()
            {
                //let's make all TabbedPanes transparent by default
                UIManager.put("TabbedPane.contentOpaque", false);

                JFrame frame = new JFrame();

                JPanel parentPanel = new JPanel();
                parentPanel.setBackground(Color.WHITE);
                frame.add(parentPanel);

                JTabbedPane tp = new JTabbedPane();               
                parentPanel.add(tp);

                //Make transparent panel
                JPanel panelTransparent = new JPanel();
                panelTransparent.setOpaque(false); // this makes panel transparent
                panelTransparent.setPreferredSize(new Dimension(200, 200));
                tp.addTab("Transparent", panelTransparent);

                //Make panel (by default panel is opaque)
                JPanel panelOpaque = new JPanel();
                tp.addTab("Opaque", panelOpaque);

                frame.setPreferredSize(new Dimension(300, 300));
                frame.pack();
                frame.setVisible(true);
            }
        };
        EventQueue.invokeLater(r);
    }
}