0

I'm having a null pointer exception and I cannot seem to find the solution. I've been searching the net for hours, but cant seem to locate my problem.

The problem is that .getText() is giving me null. Now, I cannot find a way of fixing. The code below:

import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;

public class MainPart extends JFrame
{
    private String currentuser;
    public JPanel north, center, south;
    private JButton testone, buy, sell, ButtonSetBalance, ButtonAddBalance;
    public JTextField nums, share, price, thebalance;
    public JLabel result, mybalance, myshowbalance;
    public double balance;


    public MainPart()
    {
    }


    public MainPart(String username)
    {
        currentuser = username;

        GridBagConstraints c = new GridBagConstraints();

        north = new JPanel(new GridBagLayout());
        north.setBackground(Color.cyan);
        north.setSize(300,300);
        getContentPane().add(north, BorderLayout.SOUTH);

        testone = new JButton("Start/Stop");
        c.gridx = 0;
        c.gridy = 0;
        north.add(testone, c);

        nums = new JTextField(10);
        c.gridx = 1;
        c.gridy = 0;
        north.add(nums, c);

        result = new JLabel("result");
        c.gridx = 2;
        c.gridy = 0;
        north.add(result, c);

        ButtonSetBalance = new JButton("Set Balance");
        c.gridx = 0;
        c.gridy = 1;
        north.add(ButtonSetBalance, c);

        ButtonAddBalance = new JButton("Add Balance");
        c.gridx = 1;
        c.gridy = 1;
        north.add(ButtonAddBalance, c);

        thebalance = new JTextField(10);
        c.gridx = 2;
        c.gridy = 1;
        north.add(thebalance,c);

        mybalance = new JLabel("Balance: ");
        c.gridx = 0;
        c.gridy = 2;
        north.add(mybalance, c);

        myshowbalance = new JLabel(Double.toString(balance));
        c.gridx = 1;
        c.gridy = 2;
        north.add(myshowbalance,c);

        System.out.println("The balance: " + thebalance.getText());

        newevent e = new newevent();

        testone.addActionListener(e);
        ButtonAddBalance.addActionListener(e);
        ButtonSetBalance.addActionListener(e);

    }

    public class newevent extends MainPart implements ActionListener
    {
        public boolean engine = false;
        public Thread t;
        MainPart action;        
        public void actionPerformed(ActionEvent evt)
        {   

            if(evt.getSource() == testone)
            {

                //t = new Thread(new StockNums(true));
                //t.start();

               if(engine == false)
               {
                    t = new Thread(new StockNums(true));
                    t.start();
                    System.out.println("Start");
                    engine = true;
                }
                else
                {
                    t.interrupt();
                    System.out.println("Stop");
                    engine = false;
                }

            }
            else if(evt.getSource() == ButtonSetBalance)
            {
                System.out.println("Inside set theres: ");
                try
                {
                    action = new MainPart();
                    action.setBalance(Double.parseDouble(thebalance.getText()));
                }
                catch(Exception e){System.out.println(e);}
            }
            else if(evt.getSource() == ButtonAddBalance)
            {
                try
                {
                    action = new MainPart();
                    action.addBalance(Double.parseDouble(thebalance.getText()));
                }
                catch(Exception e){ System.out.println(e);}
            }
        }
    }

    public void setBalance(double bal)
    {
        balance = bal; 
        System.out.println("Balance = £" + balance);

    }

    public void addBalance(double bal)
    {
        balance += bal;
        System.out.println("Added " + bal + " to balance. New balance = £");

    }

    public void setLabelText(String i)
    {
        result.setText(i);
    }
}

The problem is specifically in the event where it listens for ButtonAddBalance and ButtonSetBalance. It gives a NullPointerException and I have found no way of fixing. It is supposed to get text from label "thebalance" and parse it to Double, and then depending on which, it will either added to balance or set it to the balance global double variable. Thank You!

Error here:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at MainPart$newevent.actionPerformed(MainPart.java:115)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6373)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
    at java.awt.Component.processEvent(Component.java:6138)
    at java.awt.Container.processEvent(Container.java:2085)
    at java.awt.Component.dispatchEventImpl(Component.java:4735)
    at java.awt.Container.dispatchEventImpl(Container.java:2143)
    at java.awt.Component.dispatchEvent(Component.java:4565)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4621)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4282)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4212)
    at java.awt.Container.dispatchEventImpl(Container.java:2129)
    at java.awt.Window.dispatchEventImpl(Window.java:2478)
    at java.awt.Component.dispatchEvent(Component.java:4565)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:679)
    at java.awt.EventQueue.access$000(EventQueue.java:85)
    at java.awt.EventQueue$1.run(EventQueue.java:638)
    at java.awt.EventQueue$1.run(EventQueue.java:636)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
    at java.awt.EventQueue$2.run(EventQueue.java:652)
    at java.awt.EventQueue$2.run(EventQueue.java:650)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:649)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

And StockNums class here(although I dont think its needed for this error?):

import java.util.*;

public class StockNums extends MainPart implements Runnable
{
   int num;
   boolean active;
   Random r = new Random();
   MainPart n = new MainPart();

   public StockNums(boolean get)
   {
       System.out.println("Inside StockNums");
       active = get;
    }


    public void run()
    {
        try
        {
            while(active == true)
            {
                //result.setText(Double.toString(random(Integer.parseInt(nums.getText()))));
                System.out.println(Double.toString(random(1000)));
                Thread.sleep(1000); // One second refresh
            }
        }
        catch(Exception e){}
    }

    public double random(int num)
    {
        Random number = new Random();
        return number.nextInt(num); 

    }

    //result.setText(Double.toString(random(Integer.parseInt(nums.getText()))));
}
6
  • Ignore the println in ButtonSetBalance, forgot to take it out, was checking if the code was executing and locating the error. Commented Mar 15, 2012 at 17:38
  • Please always paste the full error verbatim. Otherwise people have to guess. Commented Mar 15, 2012 at 17:38
  • Where is your StockNums(boolean) constructor ? I mean the whole class :-) Commented Mar 15, 2012 at 17:39
  • Seems to me the whole coding style of yours is wrong. Why you extending the GUI class for controller class, why not put those things inside the given GUI class instead, when they have to be together at one point or the other. Many a things are wrong, or wrongly written scheme, most of them don't adhere to the standards Java had set for developers. Do you know about SwingWorker ? Don't use Thread.sleep(...) in your GUI, that might can cause flickers or freezing of your app. Commented Mar 15, 2012 at 17:49
  • Thanks for the feedback, what do you suggest? I'm a first year Computer Science student, this is for a Stock Market simulator application; I'm using Thread.sleep() so the random number for the stocks buffers every second. Timer? Commented Mar 15, 2012 at 17:57

1 Answer 1

1

Here's the problem: newevent extends MainPart (unnecessarily as far as I can tell). This means that thebalance inside newevent isn't the thebalance field from the enclosing MainPart, it's the thebalance field from the newevent itself, which is never initialized.

As noted in comments, there are various other problems with this code, but that's what's causing your NullPointerException. Remove extends MainPart and you should be able to move on.

Sign up to request clarification or add additional context in comments.

3 Comments

+1, no doubt, the code has so many flaws, it will be tough to explain one by one, until and unless, the OP won't sit face to face. With written communication it's too tough to explain.
Yep it did!! Cheers for that! I didn't know I didnt have to extend the MainPart to use its variables! I had another question with the same code: why doesnt the run() method of the thread in the StockNums class change the label of MainPart? If you un-comment the commented code inside the while loop you'll see the statement!
Without knowing what the StockNums class does, I can't really say. However, one thing worth knowing is that if you're going to read from or write to a Swing component, you need to do it in the event dispatch thread. So if you're modifying a label, you might need to wrap the setText() call in a Runnable and invoke it with SwingUtilities.invokeLater(). See docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.