使用getText()的NullPointerException

时间:2012-01-31 09:53:10

标签: java swing nullpointerexception jtextfield

我正在尝试从文本字段中获取文本,但每次运行程序时都会出现NullPointerException。我在互联网上发现的类似问题涉及文本字段被重新声明为局部变量,但我不能看到我在这里这样做。

错误是:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

在指定的行。任何帮助将不胜感激

编辑:

这个简短的程序演示了这个问题

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Test{

public static final Test application = new Test();
private JFrame jFrame = null;
private JPanel jContentPane = null, buttonsPanel = null, cardPanel = null, manualPanel = null, uploadPanel = null,
        defaultPanel = null;
private JPanel[] mainPanel = {getDefaultPanel(), getManualPanel(), getUploadPanel()};
private JButton manualButton = null, uploadButton = null, manualAssignButton = null;
private JTextField manualEntryField = null;
private JLabel manualLabel = null;

final static String DEFAULTPANEL = "Default";
final static String MANUALPANEL = "Manual";
final static String UPLOADPANEL = "Upload";

/**
 * Main method
 * @param args
 */
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            application.getJFrame().setVisible(true);
        }
    });
}

/**
 * Get the main application frame
 * @return JFrame
 */
private JFrame getJFrame() {
    if (jFrame == null) {
        jFrame = new JFrame();
        jFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        jFrame.setResizable(false);
        // Add the main content pane
        jFrame.setContentPane(getJContentPanel());
        jFrame.addWindowListener(new java.awt.event.WindowAdapter() {   
            public void windowClosing(java.awt.event.WindowEvent e) {    
                closeApplication();
            }
        });
    }
    jFrame.pack();
    jFrame.setLocationRelativeTo(null);
    return jFrame;
}

/**
 * Get main content
 * @return JPanel
 */
private JPanel getJContentPanel(){
    if (jContentPane == null) {
        jContentPane = new JPanel();
        jContentPane.setPreferredSize(new Dimension(500, 200));
        jContentPane.setLayout(new BorderLayout());
        jContentPane.add(getButtonsPanel(), BorderLayout.NORTH);
        jContentPane.add(getCardPanel(), BorderLayout.CENTER);
    }
    return jContentPane;
}

private JPanel getButtonsPanel() {
    if(buttonsPanel == null){
        buttonsPanel = new JPanel();
        buttonsPanel.setPreferredSize(new Dimension(500, 50));
        buttonsPanel.setBorder(BorderFactory.createLineBorder(Color.gray));

        manualButton = new JButton("Enter manually");
        manualButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                CardLayout cl = (CardLayout)(cardPanel.getLayout());
                cl.show(cardPanel, MANUALPANEL);
            }
        });

        uploadButton = new JButton("Upload file");
        uploadButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                CardLayout cl = (CardLayout)(cardPanel.getLayout());
                cl.show(cardPanel, UPLOADPANEL);
            }
        });

        buttonsPanel.add(manualButton);
        buttonsPanel.add(uploadButton);
    }
    return buttonsPanel;
}

private JPanel getCardPanel() {
    if(cardPanel == null){
        cardPanel = new JPanel(new CardLayout());
        cardPanel.setPreferredSize(new Dimension(500, 200));
        cardPanel.setBorder(BorderFactory.createLineBorder(Color.gray));
        cardPanel.add(mainPanel[0], DEFAULTPANEL);
        cardPanel.add(mainPanel[1], MANUALPANEL);
        cardPanel.add(mainPanel[2], UPLOADPANEL);
    }
    return cardPanel;
}

private JPanel getDefaultPanel() {
    if(defaultPanel == null){
        defaultPanel = new JPanel();
    }
    return defaultPanel;
}

private JPanel getManualPanel() {
    if(manualPanel == null){
        manualPanel = new JPanel();
        manualPanel.setLayout(new FlowLayout());

        manualEntryField = new JTextField(10);
        manualEntryField.setText("Enter code");

        manualAssignButton = new JButton("Assign");
        manualAssignButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
             // Here is the exception
            System.out.println(manualEntryField.getText().trim());
            }
        });

        manualLabel = new JLabel("Please enter a code and press assign");

        manualPanel.add(manualEntryField);
        manualPanel.add(manualAssignButton);
        manualPanel.add(manualLabel);

    }
    return manualPanel;
}

private JPanel getUploadPanel() {
    if(uploadPanel == null){
        uploadPanel = new JPanel();
    }
    return uploadPanel;
}

private void closeApplication() {
    System.exit(0);
}
}

4 个答案:

答案 0 :(得分:3)

在查看了您的SSCCE之后,我设法通过注释掉实例化的冗余Test并在构造函数中创建面板数组来解决NPE问题。 E.G。

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Test{

//public static final Test application = new Test();
private JFrame jFrame = null;
private JPanel jContentPane = null, buttonsPanel = null, cardPanel = null, manualPanel = null, uploadPanel = null,
        defaultPanel = null;
private JPanel[] mainPanel = new JPanel[3];
private JButton manualButton = null, uploadButton = null, manualAssignButton = null;
private JTextField manualEntryField = null;
private JLabel manualLabel = null;

final static String DEFAULTPANEL = "Default";
final static String MANUALPANEL = "Manual";
final static String UPLOADPANEL = "Upload";

Test() {
    mainPanel[0] = getDefaultPanel();
    mainPanel[1] = getManualPanel();
    mainPanel[2] = getUploadPanel();
}

/**
 * Main method
 * @param args
 */
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new Test().getJFrame().setVisible(true);
        }
    });
}

/**
 * Get the main application frame
 * @return JFrame
 */
private JFrame getJFrame() {
    if (jFrame == null) {
        jFrame = new JFrame();
        jFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        jFrame.setResizable(false);
        // Add the main content pane
        jFrame.setContentPane(getJContentPanel());
        jFrame.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent e) {
                closeApplication();
            }
        });
    }
    jFrame.pack();
    jFrame.setLocationRelativeTo(null);
    return jFrame;
}

/**
 * Get main content
 * @return JPanel
 */
private JPanel getJContentPanel(){
    if (jContentPane == null) {
        jContentPane = new JPanel();
        jContentPane.setPreferredSize(new Dimension(500, 200));
        jContentPane.setLayout(new BorderLayout());
        jContentPane.add(getButtonsPanel(), BorderLayout.NORTH);
        jContentPane.add(getCardPanel(), BorderLayout.CENTER);
    }
    return jContentPane;
}

private JPanel getButtonsPanel() {
    if(buttonsPanel == null){
        buttonsPanel = new JPanel();
        buttonsPanel.setPreferredSize(new Dimension(500, 50));
        buttonsPanel.setBorder(BorderFactory.createLineBorder(Color.gray));

        manualButton = new JButton("Enter manually");
        manualButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                CardLayout cl = (CardLayout)(cardPanel.getLayout());
                cl.show(cardPanel, MANUALPANEL);
            }
        });

        uploadButton = new JButton("Upload file");
        uploadButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                CardLayout cl = (CardLayout)(cardPanel.getLayout());
                cl.show(cardPanel, UPLOADPANEL);
            }
        });

        buttonsPanel.add(manualButton);
        buttonsPanel.add(uploadButton);
    }
    return buttonsPanel;
}

private JPanel getCardPanel() {
    if(cardPanel == null){
        cardPanel = new JPanel(new CardLayout());
        cardPanel.setPreferredSize(new Dimension(500, 200));
        cardPanel.setBorder(BorderFactory.createLineBorder(Color.gray));
        cardPanel.add(mainPanel[0], DEFAULTPANEL);
        cardPanel.add(mainPanel[1], MANUALPANEL);
        cardPanel.add(mainPanel[2], UPLOADPANEL);
    }
    return cardPanel;
}

private JPanel getDefaultPanel() {
    if(defaultPanel == null){
        defaultPanel = new JPanel();
    }
    return defaultPanel;
}

private JPanel getManualPanel() {
    if(manualPanel == null){
        manualPanel = new JPanel();
        manualPanel.setLayout(new FlowLayout());

        manualEntryField = new JTextField(10);
        System.out.println("creating text field");
        manualEntryField.setText("Enter code");

        manualAssignButton = new JButton("Assign");
        manualAssignButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
             // Here is the exception
            System.out.println(manualEntryField);
            System.out.println(manualEntryField.getText());
            System.out.println(manualEntryField.getText().trim());
            }
        });

        manualLabel = new JLabel("Please enter a code and press assign");

        manualPanel.add(manualEntryField);
        manualPanel.add(manualAssignButton);
        manualPanel.add(manualLabel);

    }
    return manualPanel;
}

private JPanel getUploadPanel() {
    if(uploadPanel == null){
        uploadPanel = new JPanel();
    }
    return uploadPanel;
}

private void closeApplication() {
    System.exit(0);
}
}

注意:我无法解释为什么这些更改解决了NPE,我只是在重构“可疑”代码。

答案 1 :(得分:2)

我确实解决了与NullPointerException相关的查询:

问题在于你声明了你的类变量:

JTextField manualEntryField = null;

只需写下:

private JTextField manualEntryField;

只需删除那个空的东西,反对它,其余代码就可以了。不能说为什么会发生,但可能是其他人可以。

以下是您的代码,只进行了更改,请立即尝试:

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Test{

public static final Test application = new Test();
    private JFrame jFrame = null;
    private JPanel jContentPane = null, buttonsPanel = null, cardPanel = null, manualPanel = null, uploadPanel = null, defaultPanel = null;
    private JPanel[] mainPanel = {getDefaultPanel(), getManualPanel(), getUploadPanel()};
    private JButton manualButton = null, uploadButton = null, manualAssignButton = null;
    private JTextField manualEntryField;
    private JLabel manualLabel = null;

    final static String DEFAULTPANEL = "Default";
    final static String MANUALPANEL = "Manual";
    final static String UPLOADPANEL = "Upload";

    /**
     * Main method
     * @param args
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                application.getJFrame().setVisible(true);
            }
        });
    }

    /**
     * Get the main application frame
     * @return JFrame
     */
    private JFrame getJFrame() {
        if (jFrame == null) {
            jFrame = new JFrame();
            jFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            jFrame.setResizable(false);
            // Add the main content pane
            jFrame.setContentPane(getJContentPanel());
            jFrame.addWindowListener(new java.awt.event.WindowAdapter() {   
                public void windowClosing(java.awt.event.WindowEvent e) {    
                    closeApplication();
                }
            });
        }
        jFrame.pack();
        jFrame.setLocationRelativeTo(null);
        return jFrame;
    }

    /**
     * Get main content
     * @return JPanel
     */
    private JPanel getJContentPanel(){
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setPreferredSize(new Dimension(500, 200));
            jContentPane.setLayout(new BorderLayout());
            jContentPane.add(getButtonsPanel(), BorderLayout.NORTH);
            jContentPane.add(getCardPanel(), BorderLayout.CENTER);
        }
        return jContentPane;
    }

    private JPanel getButtonsPanel() {
        if(buttonsPanel == null){
            buttonsPanel = new JPanel();
            buttonsPanel.setPreferredSize(new Dimension(500, 50));
            buttonsPanel.setBorder(BorderFactory.createLineBorder(Color.gray));

            manualButton = new JButton("Enter manually");
            manualButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    CardLayout cl = (CardLayout)(cardPanel.getLayout());
                    cl.show(cardPanel, MANUALPANEL);
                }
            });

            uploadButton = new JButton("Upload file");
            uploadButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    CardLayout cl = (CardLayout)(cardPanel.getLayout());
                    cl.show(cardPanel, UPLOADPANEL);
                }
            });

            buttonsPanel.add(manualButton);
            buttonsPanel.add(uploadButton);
        }
        return buttonsPanel;
    }

    private JPanel getCardPanel() {
        if(cardPanel == null){
            cardPanel = new JPanel(new CardLayout());
            cardPanel.setPreferredSize(new Dimension(500, 200));
            cardPanel.setBorder(BorderFactory.createLineBorder(Color.gray));
            cardPanel.add(mainPanel[0], DEFAULTPANEL);
            cardPanel.add(mainPanel[1], MANUALPANEL);
            cardPanel.add(mainPanel[2], UPLOADPANEL);
        }
        return cardPanel;
    }

    private JPanel getDefaultPanel() {
        if(defaultPanel == null){
            defaultPanel = new JPanel();
        }
        return defaultPanel;
    }

    private JPanel getManualPanel() {
        if(manualPanel == null){
            manualPanel = new JPanel();
            manualPanel.setLayout(new FlowLayout());

            manualEntryField = new JTextField(10);
            manualEntryField.setText("Enter code");

            manualAssignButton = new JButton("Assign");
            manualAssignButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                 // Here is the exception
                    System.out.println(manualEntryField.getText().trim());
                }
            });

            manualLabel = new JLabel("Please enter a code and press assign");

            manualPanel.add(manualEntryField);
            manualPanel.add(manualAssignButton);
            manualPanel.add(manualLabel);

        }
        return manualPanel;
    }

    private JPanel getUploadPanel() {
        if(uploadPanel == null){
            uploadPanel = new JPanel();
        }
        return uploadPanel;
    }

    private void closeApplication() {
        System.exit(0);
    }
}

此致

答案 2 :(得分:-2)

如果textBox为空,则此异常是正常的。试试这个 if(getText()。size()< 1)条件或使用try-catch,当你捕获异常时设置值非大小字符串“”。

答案 3 :(得分:-2)

当文本框为空时,是否单击了按钮?如果是这样,那么当你调用trim()函数时,你可以得到那个异常,所以在调用trim()之前看看getText()返回什么