当我使用Nimbus Look and Feel时,我在Nullpointerexception
获得addPropertyChangeListener
。当我使用Linux Standard LAF(Metal)时,一切正常。
这是一个模拟问题的小型Testproject!我有一个扩展JPanel并将内容提供给Frame的类。只有在满足某些条件时才会启用框架上的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);
}
这是Panel Class:
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);
}
}
就像之前所说的那样,它对金属LAF没有任何问题
答案 0 :(得分:2)
看起来您重写了addPropertyChangeListeners,并将侦听器存储在名为“changes”的List中。由于在执行构造函数的其余部分之前安装了UI,因此尚未初始化您的更改变量。
在将侦听器添加到List之前添加空测试,并在需要时实例化List(并在构造函数中执行相同操作)。我不记得初始化变量内联是否可行(我在这里没有JDK来测试并告诉你)。
或者考虑不要覆盖该方法。你为什么一开始就这样做?它看起来没必要(但如果没有代码我就无法准确说出来。)