Null Pointer Exception after checking with 'if' statement

后端 未结 2 643
逝去的感伤
逝去的感伤 2021-01-15 08:08

I\'m getting a really annoying error, saying I\'m getting a null pointer exception but there\'s an if statement to check to see if the text is null before proceeding:

<
相关标签:
2条回答
  • 2021-01-15 08:14

    My guess is either textToAdd or RF is null.

    If textToAdd is a JTextComponent (or subclass, but I'm guessing here), then its getText() method CANNOT return null. Therefore, Text CANNOT be null, as this test shows.

    package test;
    
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    
    public class TextComponentTest extends JFrame {
        JTextField tf;
    
        public TextComponentTest() {
            super();
            tf = new JTextField();
            getContentPane().add(tf);
        }
    
        public static void main(String[] args) {
            TextComponentTest test = new TextComponentTest();
            test.setVisible(true);
    
            String s = test.tf.getText();
            System.out.println(">" + s + "<");
            System.out.println(">" + s.length() + "<");
    
            test.tf.setText(null);
            s = test.tf.getText();
            System.out.println(">" + s + "<");
            System.out.println(">" + s.length() + "<");
        }
    }
    

    Output is:

    ><
    >0<
    ><
    >0<
    
    0 讨论(0)
  • 2021-01-15 08:20
     if(Text.equals(null));
    

    The above will throw a NullPointerException each time Text is null. Anytime you use the "." operator on null you get a NullPointerException.

    If you are getting a NPE after if(Text != null), please post the stack trace.

    0 讨论(0)
提交回复
热议问题