当我使用 Nimbus 外观时,我在 addPropertyChangeListener
处收到 NullpointerException
。当我使用 Linux 标准 LAF(金属)时,一切工作正常。
这是一个模拟问题的小测试项目!我有一个类,它扩展 JPanel 并向框架提供内容。框架上的 Finsih 按钮仅在满足某些条件时才会启用(在本例中为按下按钮 2)。
这是主类:
public class Main extends JFrame {
/**
*
*/
private static final long serialVersionUID = -3120562776241721109L;
private JPanel contentPane;
private JButton button;
private PropertyChangeListener changeListener;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
System.out.println(UIManager.getLookAndFeel());
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InstantiationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
button = new JButton("BUTTON");
button.setEnabled(false);
changeListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equalsIgnoreCase("state")) {
button.setEnabled((boolean) evt.getNewValue());
}
}
};
contentPane.add(button, BorderLayout.SOUTH);
Panel panel = new Panel();
contentPane.add(panel, BorderLayout.CENTER);
panel.addPropertyChangeListener(changeListener);
}
这是面板类:
public class Panel extends JPanel {
/**
*
*/
private static final long serialVersionUID = -5036784576513445229L;
private PropertyChangeSupport changes;
private boolean state;
/**
* Create the panel.
*/
public Panel() {
this.changes = new PropertyChangeSupport(this);
JButton button = new JButton("BUTTON2");
add(button);
state = false;
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
state = !state;
changes.firePropertyChange("state", null, state);
}
});
}
@Override
public void addPropertyChangeListener(PropertyChangeListener listener) {
changes.addPropertyChangeListener(listener);
}
}
正如之前所说,它与 Metal LAF 配合使用没有任何问题
最佳答案
看起来您覆盖了 addPropertyChangeListeners 并将监听器存储在名为“changes”的列表中。由于 UI 是在执行构造函数的其余部分之前安装的,因此您的更改变量尚未初始化。
在将监听器添加到列表之前添加空测试,并在需要时实例化列表(并在构造函数中执行相同操作)。我不记得内联初始化变量是否有效(而且我这里没有 JDK 来测试并告诉你这一点)。
或者考虑不重写该方法。你一开始为什么这么做?它看起来没有必要(但如果没有代码我无法准确判断)。
关于java - 仅适用于 LaF Nimbus 的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10471295/