在 MetalLookAndFeel 的两个实例之间切换



是否可以有两个不同的MetalLookAndFeel实例并在运行时在它们之间更改?我正在为一个名为 MARS(MIPS Assembly IDE(的 IDE 设计主题引擎,我要么需要一个自定义的外观和感觉,允许作每个组件的颜色,要么我将使用带有UIManager的默认MetalLookAndFeel来更改颜色。

我看了Java自己的LookAndFeel实现,但不明白我该怎么做。如果想编写CustomLookAndFeel,则没有教程可循,因此我想出了这样的解决方案。

是否可以有两个MetalLookAndFeel实例,一个颜色已更改,一个是默认值,并在运行时在它们之间切换?如果没有,可以做些什么来完成我想要做的事情?

作为一个白痴,不了解继承的实际工作原理会导致一些问题......解决方案很简单。子类MetalLookAndFeel并使用UIManager.setLookAndFeel(String className)在原始MetalLookAndFeel和子类CustomLookAndFeel之间切换。

子类CustomLookAndFeel

import javax.swing.plaf.metal.MetalLookAndFeel;
public class CustomMetalLookAndFeel extends MetalLookAndFeel {
private static final long serialVersionUID = -5415261270648192921L;
}

Main Method(需要InvokeLater等等,但我太懒了(:

public static void main(String[] args) {
UIManager.installLookAndFeel("CustomMetal", "laf.CustomMetalLookAndFeel");
try {
UIManager.setLookAndFeel("laf.CustomMetalLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
UIManager.getLookAndFeelDefaults().put("Panel.background", new ColorUIResource(Color.RED));
JFrame f = new JFrame();
JPanel p = new JPanel();
JButton j = new JButton("100000");
j.addActionListener(e -> {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(f);
});
p.add(j);
f.add(p);
f.pack();
f.setVisible(true);
}

最新更新