Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Accessing Class and passing Collection object.... 2

Status
Not open for further replies.

asiavoices

Programmer
Sep 20, 2001
90
CA
Hello again everyone,

I have a problem that I think I might know what may have caused it but I cannot figure out a way to have it work.

Basically,

1. I add items from a form (name, price, etc.) into an ArrayList (I called mine myStuff).

2. I would like to display the items dynamically on another Panel.

3. Once another button (ie. the "Print" button) is clicked it opens up a new panel to show everything.

My problem is that if I create a new ArrayList() before each addition of an item from the form, it will always be one item only and overwrites the previous record.

So how could I make sure that:

a. Everytime it adds a record, it will append it to the ArrayList (myStuff) and not overwrite it.

b. If I want to access to this ArrayList (myStuff) from a method to another method, say display for a Panel, how do I do that?



Here's a section of my code.........


/* =============================
= ItsMe class =
============================= */

public class ItsMe extends JFrame implements ActionListener

{
.............

public static void main(String[] args)
{
ItsMe myLayout = new ItsMe();
myLayout.setVisible(true);
} // End of void main() method

..................


/* ----------- Constructor ------------- */

public ItsMe()
{
.................

descriptionField = new JTextField(15);
descriptionField.addActionListener(this);

priceField = new JTextField(8);
priceField.addActionListener(this);

isTaxField = new JCheckBox("Yes", true);
isTaxField.addActionListener(this);

addButton = new JButton("Purchase");
addButton.addActionListener(this);
.....................
totalButton = new JButton("PRINT");
totalButton.addActionListener(this);
......................

} // End of my constructor






public void actionPerformed(ActionEvent buttonEvent)
{

ArrayList myStuff = new ArrayList();

try

{

Object buttonClicked = buttonEvent.getSource();


if (buttonClicked == addButton)
{
..................
variables .....


if ((descriptionField == null) || (descCharsEntered < minDescChars))
{
errorStatus = 1;
showErrorMsg(1, descCharsEntered, itemEntered);
}
else if (priceCharsEntered < minPriceChars)
{
errorStatus = 1;
showErrorMsg(2, priceCharsEntered, Double.toString(priceEntered));
}
else
{
errorStatus = 0;
Item cidx = new Item(itemEntered, priceEntered , taxValueSelected);
myStuff.add(cidx);
numrecords++;


Vector vec = new Vector(myStuff);

tempVec = new JList(vec);
shoppingCart = new JScrollPane(tempVec, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

.......
descriptionField.setText(&quot;&quot;);
priceField.setText(&quot;&quot;);
}


} // End of Purchase button


//If the SUBTOTAL button is pressed

else if (buttonClicked == subTotalButton)
{

.......

}

//If the PRINT button is pressed

else if (buttonClicked == totalButton)
{
........

}

//If the LOGOUT button is pressed

else if (buttonClicked == logOutButton)
{
System.exit(0);
}

}
catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(null, &quot;Sorry! Error in price format......&quot; );
priceField.setText(&quot;&quot;);
errorStatus = 1;
}

} // end of actionPerformed() method




} //end of ItsMe Class





/* =============================
= Item class =
============================= */

public class Item
{
private String itemName;
private double itemPrice;
private boolean itemTax = false;


/* ---- This is my default constructor ------- */

public Item(String theName, double thePrice, boolean theTax)
{
setItemName(theName);
setItemPrice(thePrice);
setItemTax(theTax);
}


/* ---- setItemName() method ------- */

public void setItemName(String theName)
{
itemName = theName;
}

/* ---- setItemPrice() method ------- */

public void setItemPrice(double thePrice)
{
itemPrice = thePrice;
}


/* ---- setItemTax() method ------- */

public void setItemTax(boolean theTax)
{
itemTax = theTax;
}


/* ---- getName() returned method ------- */

public String getName()
{
return itemName;
}

/* ---- getPrice() returned method ------- */

public double getPrice()
{
return itemPrice;
}

/* ---- getTax returned method ------- */

public boolean getTax()
{
return itemTax;
}


public String toString()
{
return &quot; &quot; + itemName + &quot; &quot; + itemPrice + &quot; &quot; + itemTax;
}


} // end of Item Class scope




Thank you!,

Christopher










 
If I'm understanding your code correctly (I just glanced at it) I think declaring myArray as a class variable instead of a method variable would help. So:

public class ItsMe extends JFrame implements ActionListener

{
...
private ArrayList myArray;
...


public ItsMe()
{
....
myArray = new ArrayList();
....
}
 
Hi cyli,

Your suggestion makes sense but I'm now getting the infamous

&quot;Exception occurred during event dispatching:
java.lang.NullPointerException
at ItsMe.actionPerformed(Christopher.java:896)
.......&quot;

error

Line 896 is where the actionPerformed method is. Specifically I've made the ff. modifications as you suggested...


public ItsMe extends JFrame
implements ActionListener

{

private ArrayList myStuff;

.....

public void actionPerformed(ActionEvent buttonEvent)
{
try
{
.....................

errorStatus = 0;
Item cidx = new Item(itemEntered, priceEntered , taxValueSelected);
line 896 --> myStuff.add(cidx);
numrecords++;

Iterator ite = myStuff.iterator();
..................
}
catch
{
.............
}

...............

} end of ItsMe class


Any ideas why I'm getting this error?

Thx,

Christopher






 
Hi,
Have you initialized the myStuff object in constructor?
If you have just declared the class variable, it means that myStuff is null.
 
Hi Vepu and everyone,

Sorry, I'm not sure what you mean by initializing the object in my constructor.

How do you initialize an object anyway?

Here's what I've done.... let me know if its correct.



public class ItsMe extends JFrame
implements ActionListener

{
/* --- intialization of variables, labels, buttons, etc. ------*/
.......

private ArrayList myStuff;

........



public static void main(String[] args)
{
ArrayList myStuff = new ArrayList();
ItsMe myLayout = new ItsMe();
myLayout.setVisible(true);
} // End of void main() method

........

/* ------- My constructor ---------*/

public ItsMe()
{
Date currentDate = new Date();

setSize(620,415);
setTitle(&quot;..... &quot; + currentDate.toString());
setBackground(new Color(204,255,204));
Dimension myGUI = getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

int xcoordinate = screenSize.width/2;
int ycoordinate = screenSize.height/2;

int halfWidth = myGUI.width/2;
int halfHeight = myGUI.height/2;

setLocation(xcoordinate - halfWidth, ycoordinate - halfHeight);

Container contentPane = getContentPane();

...............

} // End of my constructor


................



public void actionPerformed(ActionEvent buttonEvent)
{
try

{
Object buttonClicked = buttonEvent.getSource();

if (buttonClicked == addButton)
{
int descCharsEntered = descriptionField.getText().length();
................

if ((descriptionField == null) || (descCharsEntered < minDescChars))
{
errorStatus = 1;
showErrorMsg(1, descCharsEntered, itemEntered);
}
else if (priceCharsEntered < minPriceChars)
{
errorStatus = 1;
showErrorMsg(2, priceCharsEntered, Double.toString(priceEntered));
}
else
{
errorStatus = 0;
Item cidx = new Item(itemEntered, priceEntered , taxValueSelected);
myStuff.add(cidx);
numrecords++;
...............
...............

} // end of my actionPerform() method


} // end of ItsMe class


Please feel free to tell me:

1. where I should intitialize the ArrayList (I know I'm missing a step) so that

2. When I add an entry, it appends/adds to the ArrayList and not overwrite the record.

Thank you,

Christopher


 
Example:
Code:
public ItsMe() {
  myStuff = new ArrayList();
  /* rest of constructor */
}
This is the whole point of having a constructor, to initialize variables and allocate resources.
 
Hi Wushutwist and Vepo,

I have tried this before and it gave me the null pointer error.

Then I remember the scope &quot;thing&quot;.... and wouldn't you know it... it was because I entered:

ArrayList myStuff = new ArrayList();

and not

myStuff = new ArrayList();

This is something I have to work my mind around (scope). Correct me if I wrong ... I've read that you always would need to give it a reference type before creating the object.

Is this correct? Maybe both of you can shed some light.

This is my long way of saying thank you :~/ to you both.

I appreciate the time you took to clarify things for me.

Cheers,

Christopher.

 
Hi,

That's true that you need always declare a variable before you use it (i.e. define it's type).
But after you have to declared the variable, you don't have to (you mustn't) declare it again. In this case you have declared the class member variables after you can use them in any method, because the scope of those is the whole class.

So, as you know the parenthesis '{}' defines the scope of the variable -> variables declared inside of those can't be used outside, but variables declared outside of those can be used inside. Did I express myself unclear enough ?-)

You can do e.g. this:
public void somefunc()
{
int i=0;
try
{
i = getSomeNumber();
}
catch(...) { i = somethingElse(); }
System.out.println(i);
}



But can't do this:
public void somefunc()
{
try
{
int i = 0;
i = getSomeNumber(); // the scope of i is the try-segment
}
catch(...)
{
i = somethingElse(); // i Can't be seen here!!!
}
System.out.println(i); // gives error too
}

So, when you re-define the class variable, you actually create a new local variable. And, in another method, where that local variable can't be seen, the class variable is used (and that is not initialized, so it has null reference)

-Vepo


 
Thank you Vepo!

Christopher

P.s. I have another question re. displaying my ArrayList using a JScrollPane.

How can I do that?
 
One thing you need to know is that JScrollPane provides a scrollable view of a component. You need to place another component within the JScrollPane to do anything. So asking how to display an ArrayList in a JScrollPane doesn't really make sense.
 
Hello Wushutwist,

I understand it a bit better now. I may have 'described&quot; it incorrectly, so I apologize.

Thank you again,

Christopher

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top