2012-10-23 1 views
0

나는 자바에 익숙하지 않으며 널 포인터 예외가 발생합니다. 나는 그것이 어디에서 발생하는지 알지만 그 이유를 판단 할 수는 없습니다. 아래 코드 섹션에 있습니다. 이 코드는 시간 임금과 임금 및 시간 형식을 확인합니다. 여기 입력 버튼 던지는 null 포인터 예외

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

}이 두 텍스트 필드가 정의되어

+0

줄 167은 무엇입니까? –

+1

'javagui.java : 167' => 뭔가 클래스의 라인 167에 null입니다. – assylias

+7

'this.tutorTime' 또는'this.payment' 중 하나가 null이라고 추측 할 수 있습니다. –

답변

1

: 그러나,이 초기화되지 않습니다

private JTextField tutorTime; 
private JTextField payment; 

대신,이 두 가지가 있습니다 초기화 및 패널에서 사용 :

,210
private Component paymentText; 
private Component tutorTimeText; 

여전히 enterButtonActionPerformednull이다 이들 호출 NullPointerExceptiontutorTimepayment 참조있다. 두 가지 수정, tutorTime에 대한 참조를 tutorTimeText으로 바꿉니다. payment와 동일합니다.

또한 timeWage 배열도 초기화되지 있습니다
time = Double.parseDouble(((JTextField) tutorTimeText).getText()); 

, 옆에 또 다른 NullPointerException 처리해야합니다 : 당신은 즉, JTextField에 깁스를해야 할 것, 그래서이 필드는 Component로 정의 확실하지 왜 .

+0

완벽했습니다. 모두들 고마워요. 지금 일하고 있습니다. 시도해 보았지만, 서클에서 뛰고있는이 프로그램에서 일해 왔습니다. –

+0

@AndrewKFoust, 다행 이네, 기회가 생겼을 때 대답 해주세요. [수락] (http://meta.stackexchange.com/questions/16721/how-does-accept-rate-work/65088#65088)) – tenorsax