我想使用 Nimbus 外观和感觉创建一个 JTabbedPane,每个选项卡具有不同的颜色。我找到了多种更改颜色的方法,但据我所知,这些技术全局适用于具有某种状态的所有选项卡(例如将 TabbedPane:TabbedPaneTab[Enabled].backgroundPainter
的所有选项卡更改为相同的颜色)
我发现了两个有用的 SO 链接(接近但不完全是我问题的答案):
Override Swing Nimbus L&F primary color per component instance
Set the Background Color for JTabbedPane
下面是我想要实现的目标的模型图像。
*编辑 - 抱歉忘记包含演示程序源代码。 (这不会创建颜色,但会启动一个带有适当选项卡 Pane 的新窗口。):
public class TabbedPaneExample extends JFrame {
public static void main(String args[]) {
try {
for(javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.
getInstalledLookAndFeels()) {
if("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch(Exception ex) {
ex.printStackTrace();
}
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new TabbedPaneExample().setVisible(true);
}
});
}
public TabbedPaneExample(){
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
JTabbedPane pane = new JTabbedPane();
pane.addTab("Blue", new JLabel("Blue tab"));
pane.addTab("Red", new JLabel("Red tab"));
pane.addTab("Yellow", new JLabel("Yellow tab"));
this.add(pane);
pack();
}
}
*编辑 - 关于下面 zilk 的答案 - 它似乎不起作用。扩展 BasicTabbedPaneUI 会导致 Nimbus 特定渲染丢失。为了保持 Nimbus 渲染,需要扩展 SynthTabbedPaneUI
。但是,SynthTabbedPaneUI
不会调用 paintTabBackground
,而是调用 paintTabArea
,它既是 protected 方法,又是重载的私有(private)帮助器方法。看起来所有逻辑都发生在私有(private)帮助器方法中。由于 SynthTabbedPaneUI
中的私有(private)实例变量以及 SynthContext
中由 paintTabArea
使用的私有(private)代码,我无法在自己的代码中重现该私有(private)方法。
最佳答案
您可以为您的选项卡 Pane 设置扩展 BasicTabbedPaneUI 的新 UI。之后,您应该重写 PaintTabBackground 方法。试试这个代码
pane.setUI(new BasicTabbedPaneUI(){
@Override
protected void paintTabBackground(Graphics g, int tabPlacement,int tabIndex, int x, int y, int w, int h, boolean isSelected){
//default backcolor
Color bg = Color.LIGHT_GRAY;
switch(tabIndex){
case 0:
bg = Color.BLUE;
break;
case 1:
bg = Color.YELLOW;
break;
case 2:
bg = Color.RED;
break;
}
g.setColor(bg);
switch (tabPlacement){
case SwingConstants.TOP:
g.fillRect(x + 1, y + 1, w - 1, h - 1);
break;
case SwingConstants.BOTTOM:
g.fillRect(x, y, w - 1, h - 1);
break;
case SwingConstants.LEFT:
g.fillRect(x + 1, y + 1, w - 1, h - 2);
break;
case SwingConstants.RIGHT:
g.fillRect(x, y + 1, w - 1, h - 2);
break;
}
}
});
PS:不要忘记这一点
pane.setOpaque(true);
关于java - Nimbus 中的 JTabbedPane,每个选项卡具有不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36227638/