This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center




7年前关闭。





我是Java的新手,并且遇到了空指针异常。我知道它在哪里发生,但无法确定原因。它在代码的以下部分中。该代码正在验证时间工资以及工资和时间的格式。

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javagui.enterButtonActionPerformed(javagui.java:167)
    at javagui$1.actionPerformed(javagui.java:86)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)
    at java.awt.EventQueue.access$200(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:682)
    at java.awt.EventQueue$3.run(EventQueue.java:680)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:696)
    at java.awt.EventQueue$4.run(EventQueue.java:694)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)


这是代码:-

import java.awt.Component;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Andy
 */
public class javagui extends javax.swing.JPanel {


private JLabel tutorTimeLabel;
private JLabel paymentLabel;
private JScrollPane jScrollPane1;
private JTextArea reportTextArea;
private JTextField tutorTime;
private JTextField payment;
private JButton enterButton;
private JButton reportButton;
private JButton quitButton;
private Component paymentText;
private Component tutorTimeText;
//2d array
double[][] timeWage;
//position in array
int timeWageIndex = 0;
//minimum wage
double minimumWage = 6.55;
static final String lineSeparator = System.getProperty("line.separator");







/** Creates new form GUI */
public javagui() {
    initComponents();



}

/** This method is called from within the constructor to
 * initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is
 * always regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {



    tutorTimeLabel = new javax.swing.JLabel();
    paymentLabel = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    reportTextArea = new javax.swing.JTextArea();
    tutorTimeText = new javax.swing.JTextField();
    paymentText = new javax.swing.JTextField();
    enterButton = new javax.swing.JButton();
    reportButton = new javax.swing.JButton();
    quitButton = new javax.swing.JButton();

    tutorTimeLabel.setText("Enter total tutoring time in minutes:");

    paymentLabel.setText("Enter total amount earned this session:");

    reportTextArea.setColumns(20);
    reportTextArea.setRows(5);
    jScrollPane1.setViewportView(reportTextArea);

    enterButton.setText("Enter");
    enterButton.addActionListener(new java.awt.event.ActionListener() {

        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            enterButtonActionPerformed(evt);
        }
    });

    reportButton.setText("Report");
    reportButton.addActionListener(new java.awt.event.ActionListener() {
        @Override
    public void actionPerformed(java.awt.event.ActionEvent evt) {
            reportButtonActionPerformed(evt);
        }
    });

    quitButton.setText("Quit");
    quitButton.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            quitButtonActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(23, 23, 23)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 434, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(enterButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(reportButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(quitButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(tutorTimeLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(paymentLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(paymentText)
                        .addComponent(tutorTimeText, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE))))
            .addContainerGap(58, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(tutorTimeText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(24, 24, 24)
                    .addComponent(tutorTimeLabel)))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(paymentLabel)
                .addComponent(paymentText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(enterButton)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(reportButton)
                    .addGap(18, 18, 18)
                    .addComponent(quitButton)
                    .addContainerGap(320, Short.MAX_VALUE))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 426, Short.MAX_VALUE)))
    );
}// </editor-fold>




public void quitButtonActionPerformed(java.awt.event.ActionEvent evt) {
    //select to close the Calculator
    System.exit(0);

}

public void reportButtonActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    reportTextArea.setText(""); // clear previous report
        String newline = "\n";
        double timeTotal = 0;
        double wageTotal = 0;


        //Loops through each entry
        for(int i = 0; i<=timeWageIndex-1; i++){
            //Gets current entry time
            double time = timeWage[i][0];
            //Gets current entry wage
            double wage = timeWage[i][1];
            //Adds to sums
            timeTotal += time;
            wageTotal += wage;

            reportTextArea.append("Minutes = " + time + "    Earnings = $" + wage + newline);
        }

        DecimalFormat df = new DecimalFormat("#.##");
        double average = wageTotal / (timeTotal/60);
        //Displays report
        reportTextArea.append(newline + newline + "*****************************" + newline + newline + newline);
        reportTextArea.append("Report of your wages to Date:" + newline + newline);
        reportTextArea.append("Total Minutes Spent Tutoring = " + timeTotal + newline);
        reportTextArea.append("Total Earnings = $" + wageTotal + newline);
        reportTextArea.append("Average Per Hour Wage = $" + df.format(average) + newline + newline);
        reportTextArea.append("Minimum Wage is currently: $" + minimumWage + newline);

    if(average<minimumWage) {
                    reportTextArea.append("Your average wages are less than average");
                }
        else if(average>minimumWage && average < minimumWage*2.0) {
                    reportTextArea.append("Your average wages are average");
                }
        else if(average >= minimumWage*2.0) {
                    reportTextArea.append("Your average wages are above average");
                }
    }


   public void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:



    //Code Exception error messages when data keyed incorrectly for both textfields
                    double time = 0;
        double wage = 0;


                    //Validates time
        try {
            time = Double.parseDouble(tutorTime.getText());
        } catch (NumberFormatException e1) {
            JOptionPane.showMessageDialog(null, "The time must be a decimal number", "Invalid Input",JOptionPane.ERROR_MESSAGE);
        }

        //Validate wage
        try {
            wage = Double.parseDouble(payment.getText());
        } catch (NumberFormatException e1) {
            JOptionPane.showMessageDialog(null, "The wage must be a decimal number", "Invalid Input",JOptionPane.ERROR_MESSAGE);
        }

        //Time greater than 0 and less than 4 hours
        if(time<=0 || time>240){
            JOptionPane.showMessageDialog(null, "The time must greater than 0 and less than or equal to 4 hours (240 min)",
                    "Invalid Input",JOptionPane.ERROR_MESSAGE);
        }
        else{
            //Wage greater than 0
            if(wage<=0){
                JOptionPane.showMessageDialog(null, "The wage must greater than 0",
                        "Invalid Input",JOptionPane.ERROR_MESSAGE);
            }
            else{
                //update array values
                timeWage[timeWageIndex][0] = time;
                timeWage[timeWageIndex][1] = wage;

                //increment index
                timeWageIndex++;

                //Reset text for user entry
                tutorTime.setText("");
                payment.setText("");
            }
                    }
   }


}

最佳答案

定义了以下两个文本字段:

private JTextField tutorTime;
private JTextField payment;


但是,它们没有初始化,而是在面板中初始化并使用了这两个:

private Component paymentText;
private Component tutorTimeText;


不过,在enterButtonActionPerformed中,有一个对tutorTimepayment的引用,它们是null,这些调用导致NullPointerException。修复两个问题,将对tutorTime的引用替换为tutorTimeText。与payment相同。不知道为什么将这些字段定义为Component,因此您需要强制转换为JTextField,即:

time = Double.parseDouble(((JTextField) tutorTimeText).getText());


另请注意,timeWage数组也未初始化,接下来您将不得不处理另一个NullPointerException

关于java - 输入按钮抛出空指针异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13034471/

10-08 20:30