Set background color for JTabbedPane

I am using Nimbus Look and feel. I need to change the background color and foreground color of a tab in JTabbedPane, but the color is not set in JTabbedPane. I tried the methods setForeground (), setForegroundAt (), setBackground () and setBackgroundAt (), but this does not work. This is my code.


public class TabbedPaneDemo extends JFrame
{
    TabbedPaneDemo()
    {
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        }
        catch(Exception ex) {}

    setLayout(new BorderLayout());
    setBounds(100, 100, 800, 500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTabbedPane jt = new JTabbedPane();
    jt.addTab("Tab1", new JPanel());
    jt.addTab("Tab2", new JPanel());
    jt.addTab("Tab3", new JPanel());
    jt.addTab("Tab4", new JPanel());

    for( int i = 0; i < jt.getComponentCount(); i++)
    {
        jt.setForegroundAt(i, Color.RED);
        jt.setBackgroundAt(i, Color.BLACK);
    }

    add(jt);

    setVisible(true);
}

public static void main(String args[])
{
    new TabbedPaneDemo();
}

} code>

+3
source share
6 answers

, , , . - UIManager, , Nimbus . , , UIManager.setLookAndFeel(), - , :

     UIManager.put("nimbusBase", new ColorUIResource(0, 0, 0));
     UIManager.put("textForeground", new ColorUIResource(255, 0, 0));

. , , Nimbus . " Nimbus UIDefaults". - , , , Painter, .

+8

, . (JTextField, JLabel ..), JTabbedPane . ( Look and Feel) .

Look and Feels (Substance, Nimbus, , , .

, , Nimbus's. . . , , , .

, - JTabbedPane paintComponent, . , .

+3

JTabbedPane , , 5 JPanels, .

+2

.

2 . " ".

. .

/*
  ...
  Setting LAF Nimbus
  ...
*/

JTabbedPane tp = new JTabbedPane();

/*
   ...
   add tabs in TabbedPane
   ...
*/

:

        JLabel title = new JLabel(tp.getTitleAt(tabIndex));
        title.setForeground(Color.RED);
        tp.setTabComponentAt(tabIndex, title);

OMG!! !

+2

new JTabbedPane().setUI(new YourUI());

public class YourUI extends BasicTabbedPaneUI{

.....

private class ScrollableTabPanel extends JPanel implements UIResource {
public ScrollableTabPanel() {
    setLayout(null);
}

public void paintComponent(Graphics g) {

super.paintComponent(g);

g.setColor(Color.red);
g.fillRect(tabPane.getBounds());            

        }
    }

....

}

( QuadSpline , ), ,

http://a5.sphotos.ak.fbcdn.net/hphotos-ak-ash3/166028_2974620064454_896181702_n.jpg

+2

, : setForegroundAt setBackgroundAt. :

for (int i = 0; i < pane.getTabCount(); i++) {
    pane.setForegroundAt(i, foregroundColor);
    pane.setBackgroundAt(i, backgroundColor);
}

getComponentAt, :

for (int i = 0; i < pane.getTabCount(); i++) {
    pane.getComponentAt(i).setForeground(foregroundColor);
    pane.getComponentAt(i).setBackground(backgroundColor);
}

- , .

+1

Source: https://habr.com/ru/post/1736953/


All Articles