How to change background color of JTabbedPane in runtime?

廉价感情. 提交于 2019-12-20 04:15:57

问题


I have founds loads of examples that change the background color of JTabbedPane using either setBackgroundAt() and UIManager.put("JTabbedPane...")

However, I want to create an onclick event on a checkbox that changes the background color to green when you select it, and back to default when you unselect it.

I haven't been able to make that work using the above methods.

Any ideas?

PS: I can change the foreground color by using setForgroundAt() but not the background for some reason


回答1:


LAFs are free to ignore custom settings of some (visual only? don't know) JComponent properties, as documented f.i.:

It is up to the look and feel to honor this property, some may choose to ignore it.

So the outcome is highly LAF-dependent (Worksforme in Metal and Motif, not in Nimbus/Win) No easy and safe way around (except tweaking the ui delegate, which isn't a real option)




回答2:


Override the paintComponent and change the color there.

@Override
public void paintComponent(Graphics g) {
    g.setColor(new Color(color));
    g.fillRect(0, 0, getWidth(), getHeight());



回答3:


Try the following after setting the background/foreground colours of each of your tab panels. This should make the tabs at the top the same colour as the panels in the JTabbedPane (myTabs). This works for me with Nimbus.

for (int c = 0; c < myTabs.getComponentCount(); ++c)
{
  myTabs.setBackgroundAt(c, myTabs.getComponentAt(c).getBackground());
  myTabs.setForegroundAt(c, myTabs.getComponentAt(c).getForeground());
}

myTabs.setOpaque(true);
myTabs.setUI(new BasicTabbedPaneUI()); 


来源:https://stackoverflow.com/questions/13085894/how-to-change-background-color-of-jtabbedpane-in-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!