java - JFrame按钮单击NullPointerException

标签 java error-handling nullpointerexception awt

当我从欢迎的JFrame中单击一个按钮以加载到我的主框架中时,我一直收到以下错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at SRC_Main.actionPerformed(SRC_Main.java:291)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)

在我的主要frame上,我有一个nextprevious按钮,并且我使用对象数组填充一个数组来存储Cars的记录。
但是如果我自己运行Main Jframe,则可以运行nextprev按钮,因此没有无法归档的文本文件,依此类推。

为什么不“初始化”?
这是主要的代码
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.*;

import java.awt.color.*;
import java.awt.font.*;
import javax.swing.ImageIcon;
import javax.swing.border.Border;
import  sun.audio.*;    //import the sun.audio package
import  java.io.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
//end imports

public class SRC_Main extends JFrame implements ActionListener
{
    private JPanel pnl = new JPanel();
    private JPanel pnlQuote=new JPanel();
    private JButton btnNext=new JButton(new ImageIcon("C:/Users/GordonS/Desktop/SRC_MOTORS/src/Next-48.png"));
    private JButton btnPrevious=new JButton(new ImageIcon("C:/Users/GordonS/Desktop/SRC_MOTORS/src/Previous-48.png"));
    private JButton btnSound=new JButton(new ImageIcon("C:\\Users\\GordonS\\Desktop\\SRC_MOTORS\\src\\Sound-32.png"));
    private JButton btnQuoteDoc=new JButton(new ImageIcon("C:/Users/GordonS/Desktop/SRC_MOTORS/src/Document-32.png"));
    private JButton btnCalculate=new JButton(new ImageIcon("C:/Users/GordonS/Desktop/SRC_MOTORS/src/Calculator-32.png"));
    private JButton btnPrintQuote=new JButton(new ImageIcon("C:/Users/GordonS/Desktop/SRC_MOTORS/src/Print-32.png"));
    //Labels for Display
    private JLabel CarImage=new JLabel();
    private JLabel lblTitle=new JLabel("SRC_MOTORS");
    private JLabel lblSlogan=new JLabel("We search and strike for the best prices,so you don't have to!");
    private JLabel lblLikes = new JLabel();
    private JLabel lblDLikes = new JLabel();

    private JLabel quote=new JLabel("Interested in owning? Let us create a Quote for you");
    //***add Finance labels here

    //TextFields and Areas
    private JTextArea txtCarDetails = new JTextArea();

    //for MenuBar
    private JMenuBar menuB=new JMenuBar();
    private JMenu File = new JMenu("File");
    private JMenu Edit = new JMenu("Edit");
    private JMenu Home = new JMenu("Home");
    private JMenu Exit = new JMenu("Exit");
    private JMenu Quote = new JMenu("Develope Quote");
    private JMenu Print = new JMenu("Print");
    //====================================================
    private String [] carPathImg=
        {
            "C:/Users/GordonS/Desktop/SRC_MOTORS/src/RS3.jpg","C:/Users/GordonS/Desktop/SRC_MOTORS/src/FocusSTedit.jpg",
            "C:/Users/GordonS/Desktop/SRC_MOTORS/src/GR7.jpg","C:/Users/GordonS/Desktop/SRC_MOTORS/src/A45M.jpg",
            "C:/Users/GordonS/Desktop/SRC_MOTORS/src/SCIRR.jpg","C:/Users/GordonS/Desktop/SRC_MOTORS/src/M313.jpg"
        };

    //========ScannerOBJ========
    private Scanner x;
    //==========================================================================================================
    private CarsRec[] arrMasterRec;
    private static int i=0;//counter for record numbers
    private static int counter=0;
    private String RecordContent="";

    //components for finance panel
    private JLabel lblInstr=new JLabel("    Car Price:");
    private JLabel lblDepo=new JLabel("Initial Deposit:");
    private JLabel lblInt=new JLabel("Interest rate:");
    private JLabel lblyears=new JLabel("Payment Period:");
    private JLabel lblTotalcalc=new JLabel("Calculate All Info");


    private JTextField txtPrice=new JTextField(10);
    private JLabel lblTotalIntEar=new JLabel();
    private JLabel lblTotalCarAmt=new JLabel();
    private JLabel lblMonthly=new JLabel();
    private JLabel lblPaymentP=new JLabel();
    private JLabel lblPrice=new JLabel();

    private JTextField txtInitial=new JTextField("0", 10);
    private JComboBox cmbInterest =new JComboBox(new String[]{"5%","6%","7%","8%","9%"});
    private JComboBox cmbPeriod=new JComboBox(new String[]{"12","24","36","48","60"});
    private JCheckBox chkTotPayDetail=new JCheckBox();

    private JButton btnCalc=new JButton("Process");
    private JButton btnView=new JButton("View Full Quote");
    private JButton btnPrint=new JButton("Print");
    private JButton btnEmail=new JButton("Email");
    private JButton btnCancel=new JButton("Cancel Quote");

    private String Emailcont;
    private String EmailOwner;
    //==========================================================================================================
    //Constructor
    public SRC_Main() 
    {
        super("SRC_MotorsMain");
        setSize(1015,741);
        setVisible(true);
        setLayout(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);

        pnl.setLayout(null);
        pnlQuote.setLayout(new GridLayout(4,5,20,20));
        pnl.setSize(1015,741);
        pnl.setBackground(Color.DARK_GRAY);

        //Look and Feel of Components
        lblTitle.setForeground(Color.RED);
        lblTitle.setFont(new Font("Blade Runner Movie Font",0,38));

        quote.setFont(new Font("Tahoma",1,13));
        quote.setForeground(Color.RED);

        lblSlogan.setFont(new Font("Berlin Sans FB Demi",2,14));
        lblSlogan.setForeground(Color.RED);

        lblLikes.setForeground(Color.WHITE);
        lblDLikes.setForeground(Color.WHITE);

        Border border2 = BorderFactory.createLineBorder(Color.RED,5);
        pnl.setBorder(BorderFactory.createCompoundBorder(border2, 
                    BorderFactory.createEmptyBorder(5, 5, 5, 5)));


        //Editing TXTFIELDS****************************************

        txtCarDetails.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 0)), "Vehicle_Information", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Copperplate Gothic Light", 3, 14), new java.awt.Color(255, 255, 255)));
        txtCarDetails.setRows(20);
        txtCarDetails.setColumns(25);
        txtCarDetails.setEditable(false);
        txtCarDetails.setFont(new Font("Berlin Sans FB Demi",2,13));
        txtCarDetails.setBackground(Color.darkGray);
        txtCarDetails.setForeground(Color.WHITE);
        txtCarDetails.setText("Use the directional"+"\n"+" buttons to navigate through the records");
        CarImage.setIcon(new ImageIcon("C:\\Users\\GordonS\\Desktop\\SRC_MOTORS\\src\\car_front_intro"));
        //==========================================================
        CarImage.setSize(360,420);

        //Part that adds MenuBars and items
         File.add(Home);
         File.add(Exit); 
         Edit.add(Quote);
         Edit.add(Print);
         menuB.add(File);
         menuB.add(Edit);
         setJMenuBar(menuB);

         //:::::::::::::::::::::::::::::::::::::

         //******Layouts of Components*********************************************************************
         pnl.add(lblTitle);
         lblTitle.setBounds(320, 0, 290, 70);

         pnl.add(lblSlogan);
         lblSlogan.setBounds(270, 60, 390, 15);

         pnl.add(CarImage);
         CarImage.setIcon(new ImageIcon("C:\\Users\\GordonS\\Desktop\\SRC_MOTORS\\src\\car_front_intro.png"));
         CarImage.setBounds(30, 80, 360, 410);

         pnl.add(txtCarDetails);
         txtCarDetails.setBounds(520, 90, 420, 185);

         pnl.add(quote);
         quote.setBounds(510, 360, 360, 30);

         pnl.add(btnQuoteDoc);
         btnQuoteDoc.setBounds(870, 350, 30, 40);

         pnl.add(btnSound);
         btnSound.setBounds(715, 280, 40, 40);
         btnPrevious.setEnabled(false);

         pnl.add(btnNext);
         btnNext.setBounds(870, 280, 70, 40);

         pnl.add(btnPrevious);
         btnPrevious.setBounds(520, 280, 70, 40);
         btnPrevious.setEnabled(false);

         //ADD EXTRA PANEL FOR FINANCE
         pnlQuote.setBackground(Color.GRAY);
         chkTotPayDetail.setBackground(Color.GRAY);
         pnlQuote.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 0)), "SRC_FINANCE", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Copperplate Gothic Light", 3, 14), new java.awt.Color(255, 255, 255)));

         pnlQuote.add(lblInstr);
         pnlQuote.add(lblDepo);
         pnlQuote.add(lblInt);
         pnlQuote.add(lblyears);
         pnlQuote.add(lblTotalcalc);
         pnlQuote.add(txtPrice);
         txtPrice.setEditable(false);
         pnlQuote.add(txtInitial);
         pnlQuote.add(cmbInterest);
         pnlQuote.add(cmbPeriod);
         pnlQuote.add(chkTotPayDetail);
        // pnlQuote.add(new JLabel("Details: "));
         pnlQuote.add(lblPrice);
         pnlQuote.add(lblTotalIntEar);
         pnlQuote.add(lblTotalCarAmt);
         pnlQuote.add(lblMonthly);
         pnlQuote.add(lblPaymentP);
         pnlQuote.add(btnCalc);
         pnlQuote.add(btnView);
         pnlQuote.add(btnPrint);
         pnlQuote.add(btnEmail);
         pnlQuote.add(btnCancel);
         pnl.add(pnlQuote);
         pnlQuote.setBounds(490,400, 450, 270);
         pnlQuote.setVisible(false);

         //ActionListeners For Buttons
         btnNext.addActionListener(this);
         btnPrevious.addActionListener(this);
         btnQuoteDoc.addActionListener(this);

         btnView.addActionListener(this);
         btnCalc.addActionListener(this);
         btnPrint.addActionListener(this);
         btnEmail.addActionListener(this);
         btnCancel.addActionListener(this);


         i=0;
         add(pnl);
         validate();

         JOptionPane.showMessageDialog(null, "Welcome to SRC_MOTORS"+"\n"+"Our mission is to find the best Performance Modded Cars at the lowest of prices!"+"\n"+"Visit our ABOUT page for more information");
         //JOptionPane.showMessageDialog(null, "");
    }
    //********************************************END_OF_GUI*****************************************************
//---------------------------------------------------------------------------------------------------------------------------------
//==(1)Open Textfile=====================================
    public void OpenFile()
    {
        try
        {
            x=new Scanner(new File("C:/Users/GordonS/Desktop/SRC_MOTORS/src/CarRecords.txt"));
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null, "Cannot Find CarRecords! "+e);
        }
    }
//==(2)ReadTextFile======================================
    public CarsRec[] ReadFile()
    {
        int count=0;
        //Array of Objects of The Car Records class-set to Max 100 
        CarsRec [] arrRec=new CarsRec[100];

        while(x.hasNext())
        {
            String line=x.nextLine();
            String arr[]=line.split("#");
            arrRec[count]=new CarsRec(arr[0],arr[1],arr[2],arr[3],arr[4],arr[5],arr[6],arr[7],arr[8],arr[9],arr[10],arr[11]);
            count ++;
        }//close while
        x.close();//close Scanner use in txt
        return arrRec;
    }
//==(3)Preparing ArrObj for use in this class-GETMETHODS
    public void setCarRecs(CarsRec[] arr)
    {
        arrMasterRec=arr;
    }
//************************************************End TextFiles Part**********************************************************
//============================================================================================================================
    //BUTTONS ACTION AND PROCESSES
    public void actionPerformed(ActionEvent e)
    {   
        //==========NEXT==========
        if(e.getSource()==btnNext)
        {
            btnPrevious.setEnabled(true);
            btnSound.setEnabled(true);

            if(i<carPathImg.length)
            {
                RecordContent="CarID: "+arrMasterRec[i].getCarID()+"\n"+"Car Name: "+arrMasterRec[i].getName()+"\n"+"Engine Consumption: "+arrMasterRec[i].getLiter()
                        +"\n"+"Transmission Type: "+arrMasterRec[i].getTrans()+"\n"+"Year of model: "+arrMasterRec[i].getYear()+"\n"+"Mileage: "+arrMasterRec[i].getMileage()
                        +"\n"+"Modification Company: "+arrMasterRec[i].getModComp()+"\n"+"Software Stage Modded: "+arrMasterRec[i].getModStage()+"\n"+
                        "Power and Performance output: "+arrMasterRec[i].getPerformance()+"\n"+"Price: "+"R"+arrMasterRec[i].getPrice()+"\n"+"Owner Name: "+arrMasterRec[i].getCusName();

                txtCarDetails.setText(RecordContent);
                CarImage.setIcon(new ImageIcon(carPathImg[i]));

                txtPrice.setText("R "+arrMasterRec[i].getPrice()+" "+i);
                Emailcont=RecordContent;
                EmailOwner=arrMasterRec[i].getCusEmail();
                i++;

            }
            else
            {
                JOptionPane.showMessageDialog(null,"Reached end of records!");
                btnNext.setEnabled(false);
            }   
        }
        //==========================================================================================================    

        //========PREVIOUS=========
        if(e.getSource()==btnPrevious)
        {
            btnNext.setEnabled(true);
            if(i>0)
            {
            i--;
            RecordContent="CarID: "+arrMasterRec[i].getCarID()+"\n"+"Car Name: "+arrMasterRec[i].getName()+"\n"+"Engine Consumption: "+arrMasterRec[i].getLiter()
                    +"\n"+"Transmission Type: "+arrMasterRec[i].getTrans()+"\n"+"Year of model: "+arrMasterRec[i].getYear()+"\n"+"Mileage: "+arrMasterRec[i].getMileage()
                    +"\n"+"Modification Company: "+arrMasterRec[i].getModComp()+"\n"+"Software Stage Modded: "+arrMasterRec[i].getModStage()+"\n"+
                    "Power and Performance output: "+arrMasterRec[i].getPerformance()+"\n"+"Price: "+"R"+arrMasterRec[i].getPrice()+"\n"+"Owner Name: "+arrMasterRec[i].getCusName();

            txtCarDetails.setText(RecordContent);
            CarImage.setIcon(new ImageIcon(carPathImg[i]));
            txtPrice.setText("R "+arrMasterRec[i].getPrice()+" "+i);
            }
            else
            {
                JOptionPane.showMessageDialog(null,"You are currently viewing the First Record!");
                btnPrevious.setEnabled(false);
                btnSound.setEnabled(false);
            }

        }
        //===========================================================================================================


        if(e.getSource()==btnQuoteDoc)
        {
            pnlQuote.setVisible(true);
            try{
                // open the sound file as a Java input stream
                String gongFile = "C:\\Users\\GordonS\\Desktop\\SRC_MOTORS\\src\\VWSCIRROCO.aiff";
                InputStream in = new FileInputStream(gongFile);

                // create an audiostream from the inputstream
                AudioStream audioStream = new AudioStream(in);

                // play the audio clip with the audioplayer class
                AudioPlayer.player.start(audioStream);
            }
            catch(Exception ex)
            {
                JOptionPane.showMessageDialog(null, ex);
            }
        }

        if(e.getSource()==btnCalc)
        {
            double deposit=0;
            deposit=Double.parseDouble(txtInitial.getText());
            double intRate=0;
            int period=0;
            double Total=0;
            double AccumulatedAmount=0;
            double monthlyIn=0;
            double Carprice=Double.parseDouble(arrMasterRec[i].getPrice());

            //Setting intRate value
            if(cmbInterest.getSelectedIndex()==0)
            {
                intRate=(5/100);
            }
            else if(cmbInterest.getSelectedIndex()==1)
            {
                intRate=(8/100);
            }
            else if(cmbInterest.getSelectedIndex()==2)
            {
                intRate=(10/100);
            }
            else if(cmbInterest.getSelectedIndex()==3)
            {
                intRate=(12/100);
            }
            else if(cmbInterest.getSelectedIndex()==4)
            {
                intRate=(15/100);
            }
            //END
            //Setting period value
            if(cmbPeriod.getSelectedIndex()==0)
            {
                period=1;
            }
            else if(cmbPeriod.getSelectedIndex()==1)
            {
                period=2;
            }
            else if(cmbPeriod.getSelectedIndex()==2)
            {
                period=3;
            }
            else if(cmbPeriod.getSelectedIndex()==3)
            {
                period=4;
            }
            else if(cmbPeriod.getSelectedIndex()==4)
            {
                period=5;
            }
            //=======================================================

            AccumulatedAmount= (Carprice-deposit)*(1+(intRate*(period)));
            Total=AccumulatedAmount+Carprice;
            monthlyIn=Total/(period*12);

            lblPrice.setText("R "+Carprice);
            lblTotalCarAmt.setText("R "+Total);
            lblTotalIntEar.setText("R "+AccumulatedAmount);
            lblMonthly.setText("R "+Math.round(monthlyIn));
            lblPaymentP.setText(period+" months");

            QuoteLayout="\n"+"Initial Price: "+Carprice+"\n"+"Total Amount: "+Total+"\n"+"Interest Earned: "+AccumulatedAmount+
                    "\n"+"Monthly Installments: "+monthlyIn+"\n"+"Period: "+period+" Months";
        }
        //==================MENU_OPTIONS====================
        if(e.getSource()==Exit)
        {
            System.exit(0);
        }
        //==================================================
        if(e.getSource()==btnEmail)
        {
            //******************************************
            String name=JOptionPane.showInputDialog("Enter your Name: ");
             final String username="src.motortp@gmail.com";
              final String password="SRC_MOTORS123";
              String cont="Mr/Mrs "+name+"\n"+"is interested in purchasing the following advertised Vehicle :";
                System.out.println(cont);     

              Properties props= new Properties();
              props.put("mail.smtp.auth", "true");
              props.put("mail.smtp.starttls.enable", "true");
              props.put("mail.smtp.host", "smtp.gmail.com");
              props.put("mail.smtp.port", "587");

              Session session = Session.getInstance(props, new javax.mail.Authenticator()
                      {
                        protected PasswordAuthentication getPasswordAuthentication()
                        {
                            return new PasswordAuthentication(username, password);
                        }
                      });
              try
              {
                  Message message = new MimeMessage(session);
                  message.setFrom(new InternetAddress("src.motortp@gmail.com"));
                  message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("agordon03@gmail.com"));
                  message.setSubject("SRC_MOTORS on behalf of "+name);
                  message.setContent(cont+"\n"+Emailcont,"text/html");
                  Transport.send(message);
                  JOptionPane.showMessageDialog(null, "Message Sent!");
                  System.out.println("This email is successful");
              }
              catch(MessagingException err)
              {
                  throw new RuntimeException(err);
              }

            //******************************************
        }


    }
    //================================================================================================================
    private String QuoteLayout="";
    //================================================================================================================
    public static void main(String[] args) 
    {
        //new SRC_Main();
        SRC_Main read =new SRC_Main();
        read.OpenFile();
        CarsRec[] arrMRecords=read.ReadFile();
        read.setCarRecs(arrMRecords);   
    }

}

WelcomeSrc的代码
   import java.awt.*;
import java.awt.event.*;
import javafx.scene.control.ProgressBar;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.awt.color.*;
import javax.swing.Timer;


public class WelcomeSRC extends JFrame implements ActionListener
{
private JPanel pnl = new JPanel();
private JPanel pnl2 = new JPanel();
private JLabel bckPic=new JLabel();
private JProgressBar progressBar=new JProgressBar();
private JButton btnLoad=new JButton();

private JButton btnProceed=new JButton("Proceed to records...");
private Timer timer;
final static int interval=100;
int i;

    public WelcomeSRC()
    {
        super("SRC_MOTORS Home");
        setSize(1367,677);
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

         btnLoad.setFont(new Font("Berlin Sans FB Demi",2,26));
         btnLoad.setForeground(Color.RED);
         progressBar.setBackground(Color.white);
         progressBar.setForeground(Color.red);
         progressBar.setStringPainted(true);
         progressBar.setValue(0);

         btnLoad.setIcon(new ImageIcon("C:/Users/GordonS/Desktop/SRC_MOTORS/src/loading.gif"));
         btnProceed.setIcon(new ImageIcon("C:/Users/GordonS/Desktop/SRC_MOTORS/src/Login_in-32.png"));
        // btnLoad.setIcon(new ImageIcon("C:/Users/GordonS/Desktop/SRC_MOTORS/src/25.gif"));
         pnl2.setOpaque(false);
         pnl2.setLayout(null);
         pnl2.setBounds(430, 410, 420, 170);

         pnl2.add(progressBar);
         progressBar.setBounds(60, 10, 289, 20);

         pnl2.add(btnLoad);
         btnLoad.setBounds(180, 50, 40, 40);

        // pnl2.add(lblProceed);
        // lblProceed.setBounds(110, 130, 220, 40);

        progressBar.setVisible(false);
        pnl.setLayout(new BorderLayout());
        pnl.setSize(1367,677);
        bckPic.setIcon(new ImageIcon("C:/Users/GordonS/Desktop/SRC_MOTORS/src/back.png"));

        pnl.add(bckPic,BorderLayout.CENTER);

        getContentPane().add(pnl2);
        add(pnl);
        validate();
        i=0;
        btnProceed.addActionListener(this);
        btnLoad.addActionListener(this);
        //==================================================
        timer = new Timer(interval, new ActionListener() 
        {
            public void actionPerformed(ActionEvent ev)
            {
                if(i==100)
                {
                    Toolkit.getDefaultToolkit().beep();
                    timer.stop();
                //  progressBar.setValue(0);
                    JOptionPane.showMessageDialog(null, "Contents Successfully Loaded!");
                    btnLoad.hide();
                    pnl2.add(btnProceed);
                    btnProceed.setBounds(180, 50, 40, 40);
                }
                i=i+1;
                progressBar.setValue(i);
            }
        });
        //==================================================



        }
    //==================================================================
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()==btnLoad)
        {
        progressBar.setVisible(true);
        timer.restart();
        }

        if(e.getSource()==btnProceed)
        {
            SRC_Main load = new SRC_Main();

              load.setVisible(true);
             this.dispose();
        }
    }

    public static void main(String[] args) 
    {
        WelcomeSRC obj = new WelcomeSRC();  
    }

}

CarsRec类
import java.io.*;
import java.util.*;

public class CarsRec
{
    private String carID="";
    private String Name="";
    private String Liter="";
    private String Transm="";
    private String Year="";
    private String Mileage="";
    private String ModComp="";
    private String ModStage="";
    private String Perform="";
    private String Price="";
    private String CusName="";
    private String CusEmail="";

    public CarsRec(){}

    public CarsRec(String cID ,String N ,String L ,String TR ,String Y ,String M,String MDC ,String MDS ,String PF ,String PR,String CSN ,String CSE) 
    {
        carID=cID;
        Name=N;
        Liter=L;
        Transm=TR;
        Year=Y;
        Mileage=M;
        ModComp=MDC;
        ModStage=MDS;
        Perform=PF;
        Price=PR;
        CusName=CSN;
        CusEmail=CSE;
    }
    //Accessor methods
    public String getCarID()
    { return carID;}
    public String getName()
    { return Name;}
    public String getLiter()
    { return Liter;}
    public String getTrans()
    { return Transm;}
    public String getYear()
    { return Year;}
    public String getMileage()
    { return Mileage;}
    public String getModComp()
    { return ModComp;}
    public String getModStage()
    { return ModStage;}
    public String getPerformance()
    { return Perform;}
    public String getPrice()
    { return Price;}
    public String getCusName()
    { return CusName;}
    public String getCusEmail()
    { return CusEmail;}

}

最佳答案

见行号289-> if(i<carPathImg.length)
carPathImg包含6个字符串(图像路径),因此长度为6。

我认为您的输入文件"CarRecords.txt"不包含6行,每行12个单词,中间用#分隔。检查您的输入文件。
carPathImgarrMasterRec的长度必须相同。

您需要在WelcomeSRC.java中添加以下代码作为if(e.getSource()==btnProceed)

SRC_Main load =new SRC_Main();
load.OpenFile();
CarsRec[] arrMRecords=load.ReadFile();
load.setCarRecs(arrMRecords); 
load.setVisible(true);
this.dispose();

此错误是因为您传递的变量之一为null,但代码尝试使用它却并非如此。

我运行代码,它现在运行良好,没有错误,并按用户想要的次数按nextprevious按钮。没有错误。

关于java - JFrame按钮单击NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32727498/

相关文章:

java - 如何在动画结束后开始新的 Activity ?

error-handling - 为什么 "server overloaded"错误页面显然不受服务器过载的影响?

php - error_log防止显示 echo

java - 无法使用 Intent 调用其他 Activity

java - 方法引用表达式评估中空检查背后的原因是什么?

java - Eclipse 无法在 Linux Mint 中打开,Java 无法在不同目录中打开

java - 如何在 UML 中的类中显示类的实例?

java - 插入时间并计算差异的最佳mysql语句

java - 类型中的方法不适用于参数 (Class<Main>)?

插入本地数据库时出现Java空指针异常