Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

java runtime exception help

Options
  • 20-10-2010 8:15pm
    #1
    Registered Users Posts: 1,180 ✭✭✭


    hey guys, here's a watered down version of my code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    
    public class Test implements ActionListener{
        public static JTextField leftField;
        public static JTextField rightField;
        public JPanel panel;
        public JButton plus;
        public JButton clear;
        
        public static void main(String[] args) {
            Test test = new Test();
         }
         
        private Test(){
            JFrame frame = new JFrame("Calculator");
            JPanel fieldPanel = new JPanel();
            panel = new JPanel();
            
            frame.getContentPane().add(BorderLayout.NORTH, fieldPanel);
            frame.getContentPane().add(BorderLayout.CENTER, panel);
                
            fieldPanel.add(leftField);
            fieldPanel.add(rightField);
                
            plus = new JButton("+");
            panel.add(plus);
            plus.addActionListener(this);
            
            clear = new JButton("CE");
            panel.add(clear);
            clear.addActionListener(this);
            
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 200);
            frame.setVisible(true);
        }
        
        public void actionPerformed(ActionEvent event){
            leftField.setText("worked");
        }
    }
    

    and here's the error i'm getting:
    Exception in thread "main" java.lang.NullPointerException
            at java.awt.Container.addImpl(Container.java:1066)
            at java.awt.Container.add(Container.java:377)
            at Test.<init>(Test.java:25)
            at Test.main(Test.java:14)
    

    so basically the line:
    " Test test = new Test();"
    in my main method is causing the problem. can anybody tell me why? i've googled it with no success and i have used this method before when coding and never had this problem!


Comments

  • Registered Users Posts: 428 ✭✭Joneser


    Hi EyeSight, I think the problem is that you aren't initialising your JTextField variables. Try doing
    rightField = new JTextField();
    leftField = new JTextField();
    

    before you add them to your JPanel.

    Good Luck :)

    Edit: Remember not to just look at the bottom line number in your error, I only figured this out because of the one above it pointing to line 25.


Advertisement