我正在为更大的 GUI 应用程序编写脚本。主应用程序窗口使用系统的LookAndFeel
,但我希望我的脚本的 GUI 使用 Nimbus LookAndFeel
。GUI创建后,我想设置LookAndFeel
回原来的。我觉得下面的SSCCE应该可以工作,但是NullPointerException
在使用我的Component
对象时我得到了一个。
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
public class GUI extends JFrame {
private static LookAndFeel originalLookAndFeel = UIManager.getLookAndFeel();
static {
System.out.println("At start, look and feel is " + UIManager.getLookAndFeel().getName());
try {
setNimbusLookAndFeel();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("Look and feel changed to " + UIManager.getLookAndFeel().getName()
+ " before component creation");
}
private GridBagLayout gridBag = new GridBagLayout();
private JTabbedPane tabs = new JTabbedPane();
private JPanel selectionPanel = new JPanel(gridBag);
private JPanel infoPanel = new JPanel(gridBag);
private JPanel settingsPanel = new JPanel(gridBag);
public GUI() {
setWindowProperties();
setUpComponents();
addComponents();
try {
System.out.println("Setting to original, which is " + originalLookAndFeel.getName());
UIManager.setLookAndFeel(originalLookAndFeel);
System.out.println("Current look and feel is " + UIManager.getLookAndFeel().getName());
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
}
private void setWindowProperties() {
setLayout(gridBag);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(700, 600));
setTitle("fAmos Quester");
setResizable(false);
setLocationRelativeTo(null);
}
private static void setNimbusLookAndFeel() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
}
}
} catch (Exception e) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e2) {
}
}
}
public void setUpComponents() {
tabs.addTab("Quest selection", selectionPanel);
tabs.addTab("Quest info", infoPanel);
tabs.addTab("Settings", settingsPanel);
selectionPanel.setPreferredSize(new Dimension(650, 500));
infoPanel.setPreferredSize(new Dimension(650, 500));
settingsPanel.setPreferredSize(new Dimension(650, 500));
}
private void addComponents() {
add(tabs);
}
public static void main(String[] args) {
new GUI().setVisible(true);
}
}