编程语言
首页 > 编程语言> > 使用Nimbus和Java 8U20时,JList中的颜色错误

使用Nimbus和Java 8U20时,JList中的颜色错误

作者:互联网

我的应用程序使用错误的颜色为JList,因为我更新到最新的Java 8版本(U20).例如.对于所选项目而不是深蓝色,实际上使用浅灰色.

简单测试应用:

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;



public class Test {

    public Test() {
        try {
            UIManager.setLookAndFeel(new NimbusLookAndFeel());

            JList<String> l = new JList<>();
            DefaultListModel<String> model = new DefaultListModel<>();
            model.add(0, "sssssssss");
            model.add(1, "sssssssss");
            model.add(2, "sssssssss");
            model.add(3, "sssssssss");
            l.setModel(model);

            JFrame f = new JFrame();
            f.setSize(500, 500);
            f.setLocationRelativeTo(null);
            f.add(l);
            f.pack();
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setVisible(true);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }


public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            new Test();
            }
        });
    }    
}

Java 7,Java 8

Java 8 U20:

JList.getSelectionBackground()返回

DerivedColor(color=57,105,138 parent=nimbusSelectionBackground offsets=0.0,0.0,0.0,0 pColor=57,105,138

但实际上它不是RGB(57,105,138),而是上面提到的浅灰色.

解决方法:

您可以使用以下初始化代码恢复1.8.0_20之前版本的确切行为:

final NimbusLookAndFeel laf = new NimbusLookAndFeel();
UIManager.setLookAndFeel(laf);
UIDefaults defaults = laf.getDefaults();
defaults.put("List[Selected].textForeground",
    laf.getDerivedColor("nimbusLightBackground", 0.0f, 0.0f, 0.0f, 0, false));
defaults.put("List[Selected].textBackground",
    laf.getDerivedColor("nimbusSelectionBackground", 0.0f, 0.0f, 0.0f, 0, false));
defaults.put("List[Disabled+Selected].textBackground",
    laf.getDerivedColor("nimbusSelectionBackground", 0.0f, 0.0f, 0.0f, 0, false));
defaults.put("List[Disabled].textForeground",
    laf.getDerivedColor("nimbusDisabledText", 0.0f, 0.0f, 0.0f, 0, false));
defaults.put("List:\"List.cellRenderer\"[Disabled].background",
    laf.getDerivedColor("nimbusSelectionBackground", 0.0f, 0.0f, 0.0f, 0, false));

这将恢复NimbusDefaults类中1.8.0_05和1.8.0_20之间的变化.已删除参数false(通过重载方法将其有效转换为true).这种变化将Colors变成UIResources,这可能是正式的,但无论出于何种原因,它都会导致你遇到的问题.因此重新插入false会恢复旧的行为.

标签:look-and-feel,java,java-8,swing,nimbus
来源: https://codeday.me/bug/20190830/1768659.html