nullwriter
nullwriter

Reputation: 804

Error with .getText() in swing, getting NullPointerException in java

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()))));
}

Upvotes: 0

Views: 1270

Answers (1)

David Moles
David Moles

Reputation: 51073

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.

Upvotes: 1

Related Questions