有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何更改JTabbedPane的背景色?

我知道你可以{a1},但是如果不这样做,你怎么能做到这一点呢?我问这个问题只是因为setBackground似乎做不到

请注意,我希望更改以下属性:

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

共 (2) 个答案

  1. # 1 楼答案

    您还可以执行以下操作:

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

    或者

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

    用于选项卡和面板背景

  2. # 2 楼答案

    ^{}为例,setBackgroundAt()似乎有效:

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

    附录:@camickr很有帮助地观察到,目标组件必须是opaque

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