未初始化的组件抛出NUllPointerException

时间:2011-07-29 04:45:00

标签: java swing

请帮我弄清楚这里出了什么问题?刚开始用java。

public class PropertyChangeListenerTest {
private JPanel mainPanel = null;
private JTextField source = null;
private JTextField target = null;

PropertyChangeListenerTest() {

    mainPanel = new JPanel();
    mainPanel.setLayout(new GridLayout(1, 0, 10, 0));
    source = new JTextField(20);
    target = new JTextField(20);
    mainPanel.add(source);
    mainPanel.add(target);

}

JPanel getMainPanel() {
    return mainPanel;
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            createAndShowGUI();
        }
    });
}

protected static void createAndShowGUI() {
    JFrame f = new JFrame("PropertyChangeListener");
    f.getContentPane().add(new PropertyChangeListenerTest().getMainPanel());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setVisible(true);
}

}

1 个答案:

答案 0 :(得分:0)

此代码没问题。以任何方式运行此代码。意思是使用cmd。

cmd combile命令:

javac PropertyChangeListenerTest.java

java PropertyChangeListenerTest