我有一个空指针异常,我似乎找不到解决方法。我已经在网上搜索了几个小时,但似乎找不到我的问题。

问题是.getText()给我空值。现在,我找不到解决方法。下面的代码:

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


该问题特别是在侦听ButtonAddBalance和ButtonSetBalance的事件中。它给出了NullPointerException,但我找不到修复的方法。应该从标签“ thebalance”中获取文本并将其解析为Double,然后根据具体情况将其添加到balance或将其设置为balance全局double变量。谢谢!

错误在这里:

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)


和StockNums类在这里(尽管我认为此错误不需要它?):

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

最佳答案

问题出在这里:newevent扩展了MainPart(据我所知,这是不必要的)。这意味着thebalance内的newevent不是封闭的thebalanceMainPart字段,而是thebalance本身的newevent字段,该字段从未初始化。

如注释中所述,此代码还有其他各种问题,但这就是导致您的NullPointerException的原因。删除extends MainPart,您应该可以继续。

10-06 07:20