UIManager.setLookAndFeel for nested classes



是否可以设置一次外观并将其"级联"到所有嵌套类?

在下面的示例中,我在类Test中设置了外观,但是我添加到MainPanel类(嵌套在我的Test类中(的JFileChooser不会调整其外观,除非我在该类中再次设置它。

这只是我需要为我创建的每个类做的事情吗?或者有没有办法让我在所有类中应用相同的外观和感觉?

import java.awt.Dimension;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
/**
* Class to demonstrate UIManager.setLookAndFeel issue.
*/
public class Test {
/**
* Main program.
* @param args
*/
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test();
}
});
}
/**
* Constructor.
*/
public Test() {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
createGUI();
}
/**
* Set up the JFrame and add the main JPanel.
*/
public void createGUI() {
JFrame frame = new JFrame("Test");
frame.add(new MainPanel(800, 600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
frame.setLocationRelativeTo(null);
}
/**
* Class for the main panel that will hold all other components.
*/
class MainPanel extends JPanel {
private final int width;
private final int height;
/**
* Serialize/save.
*/
private static final long serialVersionUID = -3727866499459986351L;
/**
* Constructor.
*/
public MainPanel(int w, int h) {
this.width = w;
this.height = h;
// ISSUE the chooser does not have the look and feel of my OS
// unless I set the look and feel in this constructor
JFileChooser chooser = new JFileChooser();
this.add(chooser);
}
/**
* 
*/
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
}
}

"问题"在这一行:

UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());

你看到的外观和感觉是跨平台的。这是Java的原始 - yikes。

尝试将其更改为:

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

我相信它会被改变。

最新更新