I am working on part five of the Farmers Market program and am ready to pull my hair out. Not getting much help from the instructor either.

here is the code

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package farmersmarket5;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

/**
 *
 * @author Kathy Lowe
 */
class FarmersMarket5 implements ActionListener
        

{
    static JFrame jfrMain;
	// Declare 4 buttons
	static JButton jbnFirst, jbnNext, jbnPrevious, jbnLast; 

	// Declare a panel to draw on - holds labels
	static JPanel jplNavigation;

	// Declare Advanced panel for additional buttons - holds buttons
	static JPanel jplAdvanced;

	// Declare a text area
	static JTextArea jtxtArea;

	// Declare a Label
	static JLabel jlblogo, jlbLabel;

	public FarmersMarket5()
        
        {  
            //constructor
	    // Create and set up the window.
	    jfrMain = new JFrame("Farmer's Market Data Report");
	    jfrMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	    // Add the text area
	    jtxtArea = new JTextArea();
	    jtxtArea.append(Produce.getCurrentProduceString());
	    jfrMain.getContentPane().add(jtxtArea);

	    // Create Panel for label
	    jplNavigation = new JPanel();
            jlbLabel = new JLabel();
            jlbLabel.setText("Farmer's Market Program");

	    // Create Advanced panel for additional buttons
	    jplAdvanced = new JPanel();
            
            //Create First Button
            jbnFirst = new JButton ("First");
            jbnFirst.addActionListener(this);
            jbnFirst.setActionCommand("first");
            
            //Create Previous button
            jbnPrevious = new JButton ("Previous");
            jbnPrevious.addActionListener(this);
            jbnPrevious.setActionCommand("previous");
	  
	    // Create Next button
	    jbnNext = new JButton("Next");
	    jbnNext.addActionListener(this);
	    jbnNext.setActionCommand("next");
            
            //Create Last button
            jbnLast = new JButton ("Last");
            jbnLast.addActionListener (this);
            jbnLast.setActionCommand ("last");

	   

	    // Add Title label to the panel
            jplNavigation.add(jlbLabel);


	    // Add buttons to Advanced Panel           
	    jplAdvanced.add(jbnFirst);
	    jplAdvanced.add(jbnPrevious);
	    jplAdvanced.add(jbnNext);
	    jplAdvanced.add(jbnLast);
            
            // Create Logo
	    jlbLogo = new JLabel(createImageIcon("farmersmarket.gif"));

	    

	    // Add panel to frame
	    jfrMain.getContentPane().add(jplNavigation, BorderLayout.PAGE_START);
	    jfrMain.getContentPane().add(jtxtArea, BorderLayout.WEST);
	    jfrMain.getContentPane().add(jlbLogo, BorderLayout.EAST);

	    // Add Advanced panel to frame
	    jfrMain.getContentPane().add(jplAdvanced, BorderLayout.PAGE_END);

	    //Display the window.
	    jfrMain.pack();
	    jfrMain.setVisible(true);
    
    }
        
        private static void showCurrentProduce()
        {
		jtxtArea.setText(Produce.getCurrentProduceString());
	}
        
        //tells the program where to find the image file
	private static ImageIcon createImageIcon(String fileName) 
        {
		java.net.URL imgURL = FarmersMarket5.class.getResource(fileName);
		return new ImageIcon(imgURL);
        }
        public static void enableButtons(boolean enable) 
        {
		jbnFirst.setEnabled(enable);
		jbnNext.setEnabled(enable);
		jbnPrevious.setEnabled(enable);
		jbnLast.setEnabled(enable);
		
		return;
	}
        @SuppressWarnings("static-access")
	@Override
	public void actionPerformed(ActionEvent e) 
        {
		// Auto-generated method stub
		if ("first".equalsIgnoreCase(e.getActionCommand())) 
                {
			Produce.showFirst();
			showCurrentProduce();
		} else if ("previous".equalsIgnoreCase(e.getActionCommand())) 
                {
			Produce.showPrevious();
			showCurrentProduce();
		} else if ("next".equalsIgnoreCase(e.getActionCommand()))
                {
			Produce.showNext();
			showCurrentProduce();
		} else if ("last".equalsIgnoreCase(e.getActionCommand())) 
                {
			Produce.showLast();
			showCurrentProduce();
		} 
	}
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package farmersmarket5;

import java.text.NumberFormat;
import java.util.Formatter;
import java.util.Locale;

/**
 *
 * @author Kathy
 */
public class Produce 

{
    // Create an array of Produce
	static ProdDataFormat[] farmData = new ProdDataFormat[0]; //array object

	// Keep track of current Produce
	static int currentProduce = 0;


	// main method begins execution of the Java application;
	public static void main( String args[])
	{

                 //loading the array object
		addFarmData("Canteloupe","Kathy' Farm", 12345678,2, 5.00);
		addFarmData("Tomato","Bill's Farm", 87654321, 5, 3.00);
		addFarmData("Potato","Local Farm",12312312, 12, 25.00);
		addFarmData("Squash","Kathy's Farm",20947136, 4,3.00);
		addFarmData("Cucumber","Local Farm",86125390, 22,1.00);
		
		dataSort(); //call a method to sort the data

		//@Supress Warnings("unused")
		FarmersMarket5 appGUI = new FarmersMarket5(); //calls constructor

	} // end main

	public static float inventoryValue()
	{
		float total = 0;

		 for(int x = 0; x < farmData.length; x++){
			total += farmData[x].getTotalSales();
		}// end for loop

		return total;
	}

	public static void dataSort()
	{
		  ProdDataFormat tmp;

		   for (int currentProduce = 0; currentProduce < farmData.length; currentProduce++) {
			  for (int i = currentProduce + 1; i< farmData.length; i++) {
				  String s1 = farmData[currentProduce].getProdName();
				  String s2 = farmData[i].getProdName();
				  if( s1.compareTo(s2) > 0)  {
					  tmp = farmData[currentProduce];
					  farmData[currentProduce] = farmData[i];
					  farmData[i] = tmp;
				  }
			  }
		 }
	}

	
	      
        // Return a string for the current Produce

	public static String getCurrentProduceString() 
        {
		if (farmData.length == 0) {
			return "No Produce data";
		} else {
			StringBuilder sb = new StringBuilder();

			// Send all output to the Appendable object sb
			Formatter formatter = new Formatter(sb, Locale.US);

			// Build Inventory String
			formatter.format(farmData[currentProduce].toString());
			formatter.format("\n");
			formatter.format("Total Inventory Value: %s\n", NumberFormat.getCurrencyInstance().format(inventoryValue()));
			return sb.toString();
		}
	}

	// Method to increment current produce
	public static void showNext(){
		if (currentProduce == farmData.length - 1){
			showFirst();
		} else {
			currentProduce++;
		}
	}

	// Method to decrement the current DVD
	public static void showPrevious()
        {
		if (currentProduce == 0) {
			showLast();
		} else {
			currentProduce--;
		}
	}

	// Method to go to first item
	public static void showFirst(){
		currentProduce = 0;
	}

	// Method to go to last item
	public static void showLast(){
		currentProduce = farmData.length - 1;
	}

	//
	public static String[] getStringArray() {
    	String[] currentStringArray = new String[5];
        
    	currentStringArray[0] = farmData[currentProduce].getProdName();
        currentStringArray[1] = farmData[currentProduce].getFarmName();
        currentStringArray[2] = Integer.toString(farmData[currentProduce].getProdSKU());
        currentStringArray[3] = Integer.toString(farmData[currentProduce].getProdUnits());
        currentStringArray[4] = Double.toString(farmData[currentProduce].getProdPrice());
        return currentStringArray;
    }
        
        // New Method called searchProduce
        
	public static void searchData(String name) 
        {
            for (int searchData = 0; searchData < farmData.length; searchData++) 
           	
        
    		if (name.compareToIgnoreCase(farmData[searchData].getProdName()) == 0) 
                {
    			currentProduce = searchData;
    			return;
    		}
    	}


	// New Method called modifyProduce
	public static void modifyData(String[] newData) {
		farmData[currentProduce].setProdName(newData[0]);
		farmData[currentProduce].setFarmName(newData[1]);
                farmData[currentProduce].setProdSKU(Integer.valueOf(newData[2]));
		farmData[currentProduce].setProdUnits(Integer.valueOf(newData[3]));
		farmData[currentProduce].setProdPrice(Float.valueOf(newData[4]));
		dataSort();
	}
	public static int getNextFarmData() 
        {
		int newSKU = 0;
		for (int x = 0; x < farmData.length; x++) {
			if (farmData[x].getProdSKU() > newSKU) {
				newSKU = farmData[x].getProdSKU();
			}
		}
		return newSKU;
	}

	

	public static void addFarmData(String name, String farm, int SKU, int units, double price) {
		String[] newProduce = new String[5]; //create a String array
                //load the array with the items that was passed into the method
		newProduce[0] = name;
		newProduce[1] = farm;
                newProduce[2] = Integer.toString(SKU);
		newProduce[3] = Integer.toString(units);  //convert the integer pass in to a string
		newProduce[4] = Double.toString(price);
		addProduce(newProduce); //method  call
		return;

	}
        
        
	// New Method called addProduce
	//@SupressWarnings("unchecked")
	public static void addProduce(String[] data) {
		// Add a new Produce
		ProdDataFormat sDataFormat = new ProdDataFormat(getNextFarmData(), data[0], Integer.valueOf(data[3]), Double.valueOf(data[4]), data[1]);
		Class elementType = farmData.getClass().getComponentType();
		ProdDataFormat[] newArray = (ProdDataFormat[]) java.lang.reflect.Array.newInstance(elementType,farmData.length);
		System.arraycopy(farmData, 0, newArray, 0, farmData.length);

		newArray[newArray.length -1] = sDataFormat;

		farmData = newArray;
		showLast();
		dataSort();
	}
//@SuppressWarnings("unchecked")
	//public static void deleteProduce() {
    	//int salesmanToDelete = currentProduce;

    	/**
    	* Allocates an array with a new size, and copies the contents
    	* of the old array to the new array, except the deleted item.
    	* Then copies it back and adds the new item.
    	*/
	   //Class elementType = farmData.getClass().getComponentType();
	   //ProdDataFormat[] newArray = (ProdDataFormat[]) java.lang.reflect.Array.newInstance(elementType, farmData.length - 1);
	   //System.arraycopy(farmData, 0, newArray, 0, salesmanToDelete);
	  // System.arraycopy(farmData, salesmanToDelete+1, newArray, salesmanToDelete, farmData.length - ProduceToDelete - 1);
	  // farmData = newArray;
	   //// In case we delete the last produce
	  // showPrevious();
	  // dataSort();

	}

	

	//public static int getProduceDataSize() {
	//	return farmData.length;
	//}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package farmersmarket5;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.NumberFormat;
import java.util.Formatter;
import java.util.Locale;

/**
 *
 * @author Kathy Lowe
 */
class ProdDataFormat extends ProdData
{
  
    private String farmName;

	public ProdDataFormat(int SKU, String pName, int pUnits, double pPrice, String fName)
        {
		super(SKU, pName, pUnits, pPrice);
		farmName = fName;
	}

	public ProdDataFormat(int SKU, String pName, int pUnits, double pPrice) 
        {
		super (SKU, pName, pUnits, pPrice);
	}

	public ProdDataFormat(String pName) {
		super(pName);
	}


	public String getFarmName(){
		return farmName;
	}

	public void setFarmName(String fName){
		farmName = fName;
	}

	public double getTotalSales(){
		return super.getTotalSales();
	}

	public double getSalesTax() {
		return super.getTotalSales() * .07;
	}

	public String toString() {
		StringBuilder sb = new StringBuilder();


		// Send all output to the Appendable object sb
		Formatter formatter = new Formatter(sb, Locale.US);

		// Explicit argument indices may be used to re-order output.
		formatter.format("SKU: %d\n", getProdSKU());
		formatter.format("Item Name: %s\n", getProdName());
		formatter.format("Farm Name: %s\n", getFarmName());
		formatter.format("Number of Units Sold: %d\n", getProdUnits());
		formatter.format("Produce Price: %s\n", NumberFormat.getCurrencyInstance().format(getProdPrice()));
		formatter.format("Total Sales: %s\n", NumberFormat.getCurrencyInstance().format(getTotalSales()));
		formatter.format("Sales Tax: %s\n", NumberFormat.getCurrencyInstance().format(getSalesTax()));
		formatter.format("Grand Total: %s\n", NumberFormat.getCurrencyInstance().format(getTotalSales() + getSalesTax()));
		return sb.toString();
	}

	


}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package farmersmarket5;

/**
 *
 * @author Kathy
 */

class ProdData 
{
        private int prodSKU;
	private String prodName;
        private int prodUnits;
	private double prodPrice;

	public ProdData(int SKU, String pName, int pUnits, double pPrice)
                
        {
		prodSKU = SKU;
		prodName = pName;                
                prodUnits = pUnits;
		prodPrice = pPrice;

	}
	public ProdData(String pName)
        {		
                prodSKU = 0;
                prodName = pName;
                prodUnits = 0;
		prodPrice = 0;
	}

	public ProdData() 
        {
		prodSKU = 0;
		prodName = "";
                prodUnits = 0;
		prodPrice = 0;
	}

	
    //get SKU
    public int getProdSKU() 
    {
        return prodSKU;
    }

    //set SKU
    public void setProdSKU(int prodSKU) {
        this.prodSKU = prodSKU;
    }

   //get produce name
    public String getProdName() {
        return prodName;
    }

   //set produce name
    public void setProdName(String prodName) {
        this.prodName = prodName;
    }
    
   
    //get number of units sold
    public int getProdUnits() {
        return prodUnits;
    }

    // set units sold
    public void setProdUnits(int prodUnits) {
        this.prodUnits = prodUnits;
    }

    //get produce price
    public double getProdPrice() {
        return prodPrice;
    }

   //set produce price
    public void setProdPrice(double prodPrice) {
        this.prodPrice = prodPrice;
    }


// get total sales
    public double getTotalSales(){
	return prodUnits * prodPrice;
    }
}

I am working with NetBeans and when I try to run the program I get this:


run:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at farmersmarket5.Produce.addProduce(Produce.java:194)
at farmersmarket5.Produce.addFarmData(Produce.java:179)
at farmersmarket5.Produce.main(Produce.java:30)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)


If I do a clean and build I get this:


init:
deps-clean:
Updating property file: C:\Users\Kathy\Documents\NetBeansProjects\FarmersMarket5\build\built-clean.properties
Deleting directory C:\Users\Kathy\Documents\NetBeansProjects\FarmersMarket5\build
clean:
init:
deps-jar:
Created dir: C:\Users\Kathy\Documents\NetBeansProjects\FarmersMarket5\build
Updating property file: C:\Users\Kathy\Documents\NetBeansProjects\FarmersMarket5\build\built-jar.properties
Created dir: C:\Users\Kathy\Documents\NetBeansProjects\FarmersMarket5\build\classes
Created dir: C:\Users\Kathy\Documents\NetBeansProjects\FarmersMarket5\build\empty
Created dir: C:\Users\Kathy\Documents\NetBeansProjects\FarmersMarket5\build\generated-sources\ap-source-output
Compiling 4 source files to C:\Users\Kathy\Documents\NetBeansProjects\FarmersMarket5\build\classes
C:\Users\Kathy\Documents\NetBeansProjects\FarmersMarket5\src\farmersmarket5\FarmersMarket5.java:95: cannot find symbol
symbol : variable jlbLogo
location: class farmersmarket5.FarmersMarket5
jlbLogo = new JLabel(createImageIcon("farmersmarket.gif"));
^
C:\Users\Kathy\Documents\NetBeansProjects\FarmersMarket5\src\farmersmarket5\FarmersMarket5.java:102: cannot find symbol
symbol : variable jlbLogo
location: class farmersmarket5.FarmersMarket5
jfrMain.getContentPane().add(jlbLogo, BorderLayout.EAST);
^
2 errors
C:\Users\Kathy\Documents\NetBeansProjects\FarmersMarket5\nbproject\build-impl.xml:603: The following error occurred while executing this line:
C:\Users\Kathy\Documents\NetBeansProjects\FarmersMarket5\nbproject\build-impl.xml:245: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 1 second)


I need someone to give me instructions on how to use an image in netbeans and how to fix my outofbounds error.

I need someone to give me instructions on how to use an image in netbeans and how to fix my outofbounds error.

(just about Image) look for Icon in the JLabel

java.lang.ArrayIndexOutOfBoundsException: -1
at farmersmarket5.Produce.addProduce(Produce.java:194)

Look at line 194 in the Produce program. You have used an index with a value of -1
which is not a valid value for an index.
You need to test the index's value before using it to make sure it is valid.

This article has been dead for over six months. Start a new discussion instead.