QLJ
asked on
Cannot resolve symbol
Hi,
I am trying out this code to see how it works. But somehow it doesnt compile. Can someone help?
ps. sorry for that long chunk of info!
--------------------Config uration: j2sdk1.4.2_05 <Default>----------------- ---
C:\Program Files\JCreator LE\MyProjects\cart\Shoppin gCartApple t.java:51: cannot resolve symbol
symbol : class CommandButton
location: class ShoppingCartApplet
southPanel.add(new CommandButton(
^
C:\Program Files\JCreator LE\MyProjects\cart\Shoppin gCartApple t.java:53: cannot resolve symbol
symbol : class ShoppingCartRemove
location: class ShoppingCartApplet
new ShoppingCartRemove(this))) ;
^
C:\Program Files\JCreator LE\MyProjects\cart\Shoppin gCartApple t.java:54: cannot resolve symbol
symbol : class CommandButton
location: class ShoppingCartApplet
southPanel.add(new CommandButton(
^
C:\Program Files\JCreator LE\MyProjects\cart\Shoppin gCartApple t.java:56: cannot resolve symbol
symbol : class ShoppingCartOrder
location: class ShoppingCartApplet
new ShoppingCartOrder(this)));
^
C:\Program Files\JCreator LE\MyProjects\cart\Shoppin gCartApple t.java:62: cannot resolve symbol
symbol : variable AppletRegistry
location: class ShoppingCartApplet
AppletRegistry.instance(). addApplet( "Shopping Cart", this);
^
C:\Program Files\JCreator LE\MyProjects\cart\Shoppin gCartApple t.java:135 : cannot resolve symbol
symbol : variable PostSockURL
location: class ShoppingCartApplet
String response = PostSockURL.post(postURL,
^
6 errors
Process completed.
The link to the codes are posted on this website: http://www.geocities.com/qljune/code.htm
I am trying out this code to see how it works. But somehow it doesnt compile. Can someone help?
ps. sorry for that long chunk of info!
--------------------Config
C:\Program Files\JCreator LE\MyProjects\cart\Shoppin
symbol : class CommandButton
location: class ShoppingCartApplet
southPanel.add(new CommandButton(
^
C:\Program Files\JCreator LE\MyProjects\cart\Shoppin
symbol : class ShoppingCartRemove
location: class ShoppingCartApplet
new ShoppingCartRemove(this)))
^
C:\Program Files\JCreator LE\MyProjects\cart\Shoppin
symbol : class CommandButton
location: class ShoppingCartApplet
southPanel.add(new CommandButton(
^
C:\Program Files\JCreator LE\MyProjects\cart\Shoppin
symbol : class ShoppingCartOrder
location: class ShoppingCartApplet
new ShoppingCartOrder(this)));
^
C:\Program Files\JCreator LE\MyProjects\cart\Shoppin
symbol : variable AppletRegistry
location: class ShoppingCartApplet
AppletRegistry.instance().
^
C:\Program Files\JCreator LE\MyProjects\cart\Shoppin
symbol : variable PostSockURL
location: class ShoppingCartApplet
String response = PostSockURL.post(postURL,
^
6 errors
Process completed.
The link to the codes are posted on this website: http://www.geocities.com/qljune/code.htm
import the classes you need. If you have already imported them put them in your classpath.
You need to import those classes into your code
you seem to be missing a number of classes
In your case, import is not necessary. Make sure those classes are in the same directory as ShoppingCart
Well apparently in the class ShoppingCartApplet the class CommandButton is "invisible".
Did you do the right imports?
Did you do the right imports?
I meant ShoppingCartApplet
you can find them here if you don't already have them?
ASKER
yup. did that actually.. all in the same folder. but only successfully compiled to get the .class files for ObjectList, ShoppingCart, ShoppingCartEvent and ShoppingCartItem. the others couldnt compile cos "cannot resolve symbol"
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Or the CommandButton class for instance. Also make sure that the ShoppingCardOrder does indeed have a constructor that takes as parameter an object of the type you are trying to pass.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
try:
javac *.java
javac *.java
Try to add them all in your project (I see you are using JCreator) and re-compile.
if you're still missing classes, you'll find some more here:
http://www.wutka.com/hackingjava/ch6.htm
http://www.wutka.com/hackingjava/ch6.htm
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
>> the CommandButton class that was introduced in Chapter 10
That's what they say in Chapter 29,
but the code is in Chapter 9: http://www.wutka.com/hackingjava/ch9.htm
;°)
So it looks like you'll have to grab all those classes together...
That's what they say in Chapter 29,
but the code is in Chapter 9: http://www.wutka.com/hackingjava/ch9.htm
;°)
So it looks like you'll have to grab all those classes together...
GAH!
Your code is extremely hard to trace down, and I've given up :(
Here's as far as I got, if it'll help
import java.awt.*;
import java.applet.*;
import java.util.*;
import java.net.*;
import java.io.*;
import java.lang.Object;
import java.net.URL;
import java.awt.Button;
import java.awt.Event;
// This class provides a user interface for the ShoppingCart class
class ShoppingCartApplet extends Applet implements Observer {
protected ShoppingCart cart;
protected ObjectList itemList;
protected TextField customerName;
protected TextField totalField;
public ShoppingCartApplet() {
// Make this class an observer of the shopping cart
cart = new ShoppingCart();
cart.addObserver(this);
// Create the list of objects in the cart
itemList = new ObjectList();
// Create the field for the total cost so far
totalField = new TextField(10);
totalField.setEditable(fal se);
totalField.setText("Total: " + cart.total);
setLayout(new BorderLayout());
// Create a field for the customer name
customerName = new TextField(20);
// Combine the label and the name field on a single panel
Panel namePanel = new Panel();
namePanel.add(new Label("Customer Name: "));
namePanel.add(customerName );
// Put the name field up at the top and the item list in the center
add("North", namePanel);
add("Center", itemList);
// Create buttons for removing items and placing an order and put
// them along the bottom.
Panel southPanel = new Panel();
southPanel.add(
new CommandButton("Remove Item"));//, new ShoppingCartRemove(this))) ;
southPanel.add(
new CommandButton("Place Order"));//, new ShoppingCartOrder(this)));
southPanel.add(totalField) ;
add("South", southPanel);
// Tell the applet registry about this applet
AppletRegistry.instance(). addApplet( "Shopping Cart", this);
}
public String makeItemString(ShoppingCar tItem item) {
return item.itemName + " Qty: " + item.quantity + " Cost: "
+ item.itemCost;
}
public void update(Observable whichCart, Object ob) {
ShoppingCartEvent event = (ShoppingCartEvent) ob;
if (event.eventType == ShoppingCartEvent.ADDED_IT EM) {
// If there is a new item in the cart, add it to the scrollable list
itemList.addObject(makeIte mString(ev ent.item), event.item);
totalField.setText("Total: " + cart.total);
itemList.validate();
} else if (event.eventType == // If an item has been removed from the cart, remove it from the list
ShoppingCartEvent.REMOVED_ ITEM) {
itemList.delObject(event.i tem);
totalField.setText("Total: " + cart.total);
itemList.validate();
} else if (event.eventType == ShoppingCartEvent.CHANGED_ ITEM) {
// If an item has changed, update the list
int index = itemList.indexOf(event.ite m);
itemList.replaceObject(mak eItemStrin g(event.it em), event.item, index);
totalField.setText("Total: " + cart.total);
itemList.validate();
}
}
// If the user clicks on "Remove Item," remove it from he list
public void doRemove() {
Object ob = itemList.getSelectedObject ();
if (ob == null) {
return;
}
ShoppingCartItem item = ((ShoppingCartItem) ob).copy();
item.quantity = 1;
cart.removeItem(item);
}
// doPlaceOrder uses PostSockURL to post the order to a web
// server. You will need to customize this method to fit your needs.
public void doPlaceOrder() {
try {
URL postURL = new URL(getDocumentBase().getP rotocol(),
getDocumentBase().getHost( ), getDocumentBase().getPort( ),
"/shopping");
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
PrintStream outStream = new PrintStream(byteOut);
outStream.println("Custnam e: " + customerName.getText());
ShoppingCartItem[] items = cart.getItems();
for (int i = 0; i < items.length; i++) {
outStream.println(items[i] .itemName + "|" + items[i].quantity);
}
String response = PostSockURL.post(postURL, byteOut.toString());
System.out.println(respons e);
} catch (Exception e) {
e.printStackTrace();
}
}
public ShoppingCart getShoppingCart() {
return cart;
}
}
// This class contains data for an individual item in a
// shopping cart.
class ShoppingCartItem implements Cloneable
{
public String itemName;
public int itemCost;
public int quantity;
public URL descriptionURL;
public ShoppingCartItem()
{
}
public ShoppingCartItem(String itemName, int itemCost,
int quantity, URL descriptionURL)
{
this.itemName = itemName;
this.itemCost = itemCost;
this.quantity = quantity;
this.descriptionURL = descriptionURL;
}
// The add method is a quick method for combining two similar
// items. It doesn't perform any checks to insure that they are
// similar, however. You use this method when adding items to a
// cart, rather than storing two instances of the same item, you
// add the quantities together.
public void add(ShoppingCartItem otherItem)
{
this.quantity = this.quantity + otherItem.quantity;
}
// The subtract method is similar to the add method, but it
// removes a certain quantity of items.
public void subtract(ShoppingCartItem otherItem)
{
this.quantity = this.quantity - otherItem.quantity;
}
// You can store items in a hash table if you implement hashCode. It's
// always a good idea to do this.
public int hashCode()
{
return itemName.hashCode() + itemCost;
}
// The equals method does something a little dirty here, it only
// compares the item names and item costs. Technically, this is
// not the way that equals was intended to work.
public boolean equals(Object other)
{
if (this == other) return true;
if (!(other instanceof ShoppingCartItem))
return false;
ShoppingCartItem otherItem =
(ShoppingCartItem) other;
return (itemName.equals(otherItem .itemName) ) &&
(itemCost == otherItem.itemCost);
}
// Create a copy of this object
public ShoppingCartItem copy()
{
return new ShoppingCartItem(itemName, itemCost,
quantity, descriptionURL);
}
// Create a printable version of this object
public String toString()
{
return itemName+" cost: "+itemCost+" qty: "+quantity+" desc: "+
descriptionURL;
}
}
class ShoppingCartEvent
{
// Define the kinds of changes that can take place
public static final int ADDED_ITEM = 1;
public static final int REMOVED_ITEM = 2;
public static final int CHANGED_ITEM = 3;
// item is the item that is affected
public ShoppingCartItem item;
// eventType is the kind of change that has taken
// place (add/remove/change)
public int eventType;
public ShoppingCartEvent()
{
}
public ShoppingCartEvent(Shopping CartItem item,
int eventType)
{
this.item = item;
this.eventType = eventType;
}
}
// This class is a simple container of shopping cart items.
// It is observable, which means that it notifies any interested
// classes whenever it changes.
class ShoppingCart extends Observable
{
protected Vector items; // the items in the cart
protected int total; // the total item cost so far
public ShoppingCart()
{
items = new Vector();
total = 0;
}
// Add a new item and update the total
public void addItem(ShoppingCartItem newItem)
{
// See if there's already an item like this in the cart
int currIndex = items.indexOf(newItem);
ShoppingCartEvent event = new ShoppingCartEvent();
if (currIndex == -1) {
// If the item is new, add it to the cart
items.addElement(newItem);
event.item = newItem;
event.eventType = ShoppingCartEvent.ADDED_IT EM;
} else {
// If there is a similar item, just add the quantities
ShoppingCartItem currItem =
(ShoppingCartItem)
items.elementAt(currIndex) ;
currItem.add(newItem);
event.item = currItem;
event.eventType = ShoppingCartEvent.CHANGED_ ITEM;
}
total += newItem.itemCost * newItem.quantity;
// Tell the observers what just happened
setChanged();
notifyObservers(event);
}
// Remove item removes an item from the cart. Since it removes
// n items from the cart at a time, if there are more than n items
// in the cart, it just subtracts n from the quantity.
public void removeItem(ShoppingCartIte m oldItem)
{
// Find this object in the cart
int currIndex = items.indexOf(oldItem);
ShoppingCartEvent event = new ShoppingCartEvent();
if (currIndex == -1) {
// If it wasn't there, just return, assume everything's okay
return;
} else {
ShoppingCartItem currItem =
(ShoppingCartItem)
items.elementAt(currIndex) ;
// If you are trying to subtract more items than are in the cart,
// adjust the amount you want to subtract so it is equal to the
// number of items in the cart.
if (oldItem.quantity > currItem.quantity) {
oldItem.quantity = currItem.quantity;
}
// Adjust the total
total -= oldItem.itemCost * oldItem.quantity;
currItem.subtract(oldItem) ;
event.item = currItem;
event.eventType = ShoppingCartEvent.CHANGED_ ITEM;
// If the quantity drops to 0, remove the item entirely
if (currItem.quantity == 0) {
items.removeElementAt(curr Index);
event.eventType =
ShoppingCartEvent.REMOVED_ ITEM;
}
}
// Tell everyone what happened
setChanged();
notifyObservers(event);
}
// getItems returns a copy of all the items in the cart
public ShoppingCartItem[] getItems()
{
ShoppingCartItem[] itemArray =
new ShoppingCartItem[items.siz e()];
items.copyInto(itemArray);
return itemArray;
}
}
// This class is a special version of a scrollable list that
// associates an object with each element in the list.
class ObjectList extends java.awt.List
{
Vector objects; // the objects that correspond to list entries
public ObjectList()
{
objects = new Vector();
}
public ObjectList(int items, boolean multiSelect)
{
super(items, multiSelect);
objects = new Vector();
}
public synchronized void addObject(Object ob)
{
// add a string version of the object to the list
super.addItem(ob.toString( ));
// add the object itself to the object vector
objects.addElement(ob);
}
public synchronized void addObject(Object ob, int position)
{
// add a string version of the object to the list
super.addItem(ob.toString( ), position);
// add the object itself to the object vector
if (position >= objects.size()) {
objects.addElement(ob);
} else {
objects.insertElementAt(ob .toString( ),
position);
}
}
public synchronized void addObject(String label, Object ob)
{
// Allow the object to be assigned a label independently of the object
super.addItem(label);
objects.addElement(ob);
}
public synchronized void addObject(String label, Object ob,
int position)
{
// Allow the object to be assigned a label independently of the object
super.addItem(label, position);
if (position >= objects.size()) {
objects.addElement(ob);
} else {
objects.insertElementAt(ob .toString( ),
position);
}
}
public synchronized void delObject(Object ob)
{
// See if the object is in the vector
int index = objects.indexOf(ob);
// If not, just return
if (index < 0) return;
// Remove the object from the vector
objects.removeElementAt(in dex);
// Remove the list entry
super.delItem(index);
}
public synchronized Object getSelectedObject()
{
// Get the index of the current selection
int i = getSelectedIndex();
if (i == -1) return null;
// Return the object currently selected
return objects.elementAt(i);
}
public synchronized Object[] getSelectedObjects()
{
// Get the indices of all the selected objects
int[] selectedItems = getSelectedIndexes();
// Create an array of all the selected objects
Object[] whichObjects = new Object[
selectedItems.length];
for (int i=0; i < selectedItems.length; i++) {
whichObjects[i] = objects.elementAt(i);
}
return whichObjects;
}
public int indexOf(Object ob)
{
// Locate a particular object
return objects.indexOf(ob);
}
public Object objectAt(int index)
{
// Return the object at a particular index
return objects.elementAt(index);
}
public void replaceObject(Object ob, int index)
{
// Change a specific entry in the vector
replaceItem(ob.toString(), index);
// Change a specific entry in the list
objects.setElementAt(ob, index);
}
public void replaceObject(String label, Object ob, int index)
{
// Change a specific entry in the vector
replaceItem(label, index);
// Change a specific entry in the list
objects.setElementAt(ob, index);
}
}
// This class represents the catalog portion of a shopping cart.
// You can select items and then either view a description of
// the item or add the item to the shopping cart.
class ItemPickerApplet extends Applet implements Observer
{
ObjectList items;
ShoppingCart cart;
AppletRegistry registry;
public void init()
{
// Watch the applet registry to see when the Shopping Cart applet
// becomes active
registry = AppletRegistry.instance();
registry.addObserver(this) ;
items = new ObjectList();
// Get the URL of the list of items that are for sale
String itemURL = getParameter("itemList");
if (itemURL != null) fetchItems(itemURL);
// Put the items in the center of the screen
setLayout(new BorderLayout());
add("Center", items);
checkForShoppingCart();
// Add this applet to the registry
registry.addApplet("Item Picker", this);
}
public void checkForShoppingCart()
{
// See if the shopping cart has been loaded yet
Applet applet = registry.findApplet("Shopp ing Cart");
if (applet == null) return;
ShoppingCartApplet cartApplet = (ShoppingCartApplet)
applet;
// Get the shopping cart used by the shopping cart applet
cart = cartApplet.getShoppingCart ();
// Create the panel for adding items
Panel southPanel = new Panel();
// Set up some command buttons for adding and describing items
southPanel.add(new CommandButton("Describe Item",
new ItemPickerDescribe(this))) ;
southPanel.add(new CommandButton("Add Item",
new ItemPickerAdd(this)));
add("South", southPanel);
}
public void update(Observable obs, Object ob)
{
if (cart != null) return;
checkForShoppingCart();
}
// When someone presses the "Add Item" button, the doAdd method
// is called.
public void doAdd()
{
// Find out what object was selected
Object ob = items.getSelectedObject();
if (ob == null) return;
// Add the item to the cart
cart.addItem(((ShoppingCar tItem)ob). copy());
}
// When someone presses "Describe Item", the doDescribe method
// is called.
public void doDescribe()
{
// Find out which object was selected
Object ob = items.getSelectedObject();
if (ob == null) return;
ShoppingCartItem item = (ShoppingCartItem) ob;
// If it has a description URL, open it up in another frame
if (item.descriptionURL != null) {
getAppletContext().showDoc ument(
item.descriptionURL, "descframe");
}
}
// parseItem extracts an item name, cost, and URL from a string. The
// items should be separated by |'s.
public void parseItem(String str)
{
StringTokenizer tokenizer = new StringTokenizer(str, "|");
if (tokenizer.countTokens() < 3) return;
String name = tokenizer.nextToken();
int cost = 0;
try {
cost = Integer.parseInt(tokenizer .nextToken ());
} catch (Exception ignore) {
}
URL descURL = null;
try {
descURL = new URL(tokenizer.nextToken()) ;
} catch (Exception ignore) {
}
items.addObject(name,
new ShoppingCartItem(name, cost, 1, descURL));
}
// fetchItems gets a list of available items from the web server and
// uses parseItem to parse the individual items. If a line begins with
// the # character, it is ignored (# is typically a comment character).
public void fetchItems(String urlName)
{
try {
URL url = new URL(urlName);
DataInputStream inStream =
new DataInputStream(
url.openStream());
String line;
while ((line = inStream.readLine()) != null) {
if (line.charAt(0) == '#') continue;
parseItem(line);
}
} catch (Exception e) {
}
}
}
class ItemPickerDescribe extends Object implements Command
{
ItemPickerApplet cart;
public ItemPickerDescribe(ItemPic kerApplet cart)
{
this.cart = cart;
}
public void doCommand()
{
cart.doDescribe();
}
}
// This class implements an applet registry where applets
// can locate each other. It is an observable, so if you want
// to wait for a particular class, you can be an observer. This
// is better than the polling you have to do with getApplet.
//
// This class is implemented as a singleton, which means there
// is only one. The single instance is kept in a protected
// static variable and returned by the instance() method.
class AppletRegistry extends Observable
{
// The single copy of the registry
protected static AppletRegistry registry;
// The table of applets
protected Hashtable applets;
// Used for generating unique applet names
protected int nextUnique;
protected AppletRegistry()
{
applets = new Hashtable();
nextUnique = 0;
}
// Returns the long instance of the registry. If there isn't a registry
// yet, it creates one.
public synchronized static AppletRegistry instance()
{
if (registry == null) {
registry = new AppletRegistry();
}
return registry;
}
// Adds a new applet to the registry - stores it in the table and
// sends a notification to its observers.
public synchronized void addApplet(String name, Applet newApplet)
{
applets.put(name, newApplet);
setChanged();
notifyObservers(new AppletRegistryEvent(
AppletRegistryEvent.ADD_AP PLET,
name, newApplet));
}
// Adds a new applet to the registry - stores it in the table and
// sends a notification to its observers. If uniqueName is false, the
// applet's name is non-unique. Store the applet in a table with a
// unique version of the name (appends <#> to the name where # is
// a constantly increasing number).
public synchronized void addApplet(String name, Applet newApplet,
boolean uniqueName)
{
if (!uniqueName && (applets.get(name) != null)) {
name = name + "<"+nextUnique+">";
nextUnique++;
}
applets.put(name, newApplet);
setChanged();
notifyObservers(new AppletRegistryEvent(
AppletRegistryEvent.ADD_AP PLET,
name, newApplet));
}
// removes an applet from the table and notifies the observers
public synchronized void removeApplet(Applet applet)
{
Enumeration e = applets.keys();
while (e.hasMoreElements()) {
Object key = e.nextElement();
if (applets.get(key) == applet) {
applets.remove(key);
setChanged();
notifyObservers(new AppletRegistryEvent(
AppletRegistryEvent.REMOVE _APPLET,
(String)key, applet));
return;
}
}
}
// removes an applet from the table and notifies the observers
public synchronized void removeApplet(String name)
{
Applet applet = (Applet) applets.get(name);
if (applet == null) return;
applets.remove(name);
setChanged();
notifyObservers(new AppletRegistryEvent(
AppletRegistryEvent.REMOVE _APPLET,
name, applet));
}
// finds an applet by name, or returns null if not found
public Applet findApplet(String name)
{
return (Applet) applets.get(name);
}
// lets you see all the applets in the registry
public Enumeration getApplets()
{
return applets.elements();
}
}
interface Command
{
public void doCommand();
}
// This class implements a Button that supports the
// Command interface. When the button is pressed, it
// invokes the doCommand method in the Command interface.
class CommandButton extends Button
{
// The interface where we will invoke doCommand
protected Command buttonCommand;
// It's always polite to implement the empty constructor if
// you can get away with it.
public CommandButton()
{
}
// Allow a CommandButton with a command but no label
public CommandButton(Command command)
{
buttonCommand = command;
}
// Allow a CommandButton to use the typical Button constructor
public CommandButton(String label)
{
super(label);
}
// The most useful constructor allows a label and a command
public CommandButton(String label, Command command)
{
super(label);
buttonCommand = command;
}
// When we get an action event, invoke doCommand in buttonCommand
public boolean action(Event evt, Object which)
{
// Make sure the action event is for this object
if (evt.target != this) return false;
// Make sure we have a buttonCommand defined!
if (buttonCommand == null) return false;
buttonCommand.doCommand();
return true;
}
// Since you can create a CommandButton without passing it a
// Command interface, you need to be able to set the command later.
public void setCommand(Command command)
{
buttonCommand = command;
}
}
// This applet shows you how to open up a socket to an HTTP server
// and post data to a server. It posts information to one of the
// example CGI programs set up by the NCSA.
class PostSockURL extends Object
{
static String post(URL a,String e){return "";} //who knows what this maniac is on about????
public static void main(String args[])
{
try {
// Open up a socket to the Web server where this applet came from
Socket sock = new Socket("hoohoo.ncsa.uiuc.e du", 80);
// Get input and output streams for the socket connection
DataInputStream inStream = new DataInputStream(
sock.getInputStream());
DataOutputStream outStream = new DataOutputStream(
sock.getOutputStream());
// This request is what is sent by the NCSA's example form
String request = "button=on\r\n";
// Send the POST request to the server
// The request is of the form: POST filename HTTP/1.0
outStream.writeBytes("POST /cgi-bin/test-cgi/foo "+
" HTTP/1.0\r\n");
// Next, send the content type (don't forget the \r\n)
outStream.writeBytes(
"Content-type: application/octet-stream\r \n");
// Send the length of the request
outStream.writeBytes(
"Content-length: "+request.length()+"\r\n") ;
// Send a \r\n to indicate the end of the header
outStream.writeBytes("\r\n ");
// Now send the information you are posting
outStream.writeBytes(reque st);
// Dump the response to System.out
int ch;
while ((ch = inStream.read()) >= 0) {
System.out.print((char) ch);
}
// We're done with the streams, so close them
inStream.close();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//some bullshit class I made up to get the program to compile
class ItemPickerAdd{
ItemPickerAdd(Object e){}
}
Your code is extremely hard to trace down, and I've given up :(
Here's as far as I got, if it'll help
import java.awt.*;
import java.applet.*;
import java.util.*;
import java.net.*;
import java.io.*;
import java.lang.Object;
import java.net.URL;
import java.awt.Button;
import java.awt.Event;
// This class provides a user interface for the ShoppingCart class
class ShoppingCartApplet extends Applet implements Observer {
protected ShoppingCart cart;
protected ObjectList itemList;
protected TextField customerName;
protected TextField totalField;
public ShoppingCartApplet() {
// Make this class an observer of the shopping cart
cart = new ShoppingCart();
cart.addObserver(this);
// Create the list of objects in the cart
itemList = new ObjectList();
// Create the field for the total cost so far
totalField = new TextField(10);
totalField.setEditable(fal
totalField.setText("Total:
setLayout(new BorderLayout());
// Create a field for the customer name
customerName = new TextField(20);
// Combine the label and the name field on a single panel
Panel namePanel = new Panel();
namePanel.add(new Label("Customer Name: "));
namePanel.add(customerName
// Put the name field up at the top and the item list in the center
add("North", namePanel);
add("Center", itemList);
// Create buttons for removing items and placing an order and put
// them along the bottom.
Panel southPanel = new Panel();
southPanel.add(
new CommandButton("Remove Item"));//, new ShoppingCartRemove(this)))
southPanel.add(
new CommandButton("Place Order"));//, new ShoppingCartOrder(this)));
southPanel.add(totalField)
add("South", southPanel);
// Tell the applet registry about this applet
AppletRegistry.instance().
}
public String makeItemString(ShoppingCar
return item.itemName + " Qty: " + item.quantity + " Cost: "
+ item.itemCost;
}
public void update(Observable whichCart, Object ob) {
ShoppingCartEvent event = (ShoppingCartEvent) ob;
if (event.eventType == ShoppingCartEvent.ADDED_IT
// If there is a new item in the cart, add it to the scrollable list
itemList.addObject(makeIte
totalField.setText("Total:
itemList.validate();
} else if (event.eventType == // If an item has been removed from the cart, remove it from the list
ShoppingCartEvent.REMOVED_
itemList.delObject(event.i
totalField.setText("Total:
itemList.validate();
} else if (event.eventType == ShoppingCartEvent.CHANGED_
// If an item has changed, update the list
int index = itemList.indexOf(event.ite
itemList.replaceObject(mak
totalField.setText("Total:
itemList.validate();
}
}
// If the user clicks on "Remove Item," remove it from he list
public void doRemove() {
Object ob = itemList.getSelectedObject
if (ob == null) {
return;
}
ShoppingCartItem item = ((ShoppingCartItem) ob).copy();
item.quantity = 1;
cart.removeItem(item);
}
// doPlaceOrder uses PostSockURL to post the order to a web
// server. You will need to customize this method to fit your needs.
public void doPlaceOrder() {
try {
URL postURL = new URL(getDocumentBase().getP
getDocumentBase().getHost(
"/shopping");
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
PrintStream outStream = new PrintStream(byteOut);
outStream.println("Custnam
ShoppingCartItem[] items = cart.getItems();
for (int i = 0; i < items.length; i++) {
outStream.println(items[i]
}
String response = PostSockURL.post(postURL, byteOut.toString());
System.out.println(respons
} catch (Exception e) {
e.printStackTrace();
}
}
public ShoppingCart getShoppingCart() {
return cart;
}
}
// This class contains data for an individual item in a
// shopping cart.
class ShoppingCartItem implements Cloneable
{
public String itemName;
public int itemCost;
public int quantity;
public URL descriptionURL;
public ShoppingCartItem()
{
}
public ShoppingCartItem(String itemName, int itemCost,
int quantity, URL descriptionURL)
{
this.itemName = itemName;
this.itemCost = itemCost;
this.quantity = quantity;
this.descriptionURL = descriptionURL;
}
// The add method is a quick method for combining two similar
// items. It doesn't perform any checks to insure that they are
// similar, however. You use this method when adding items to a
// cart, rather than storing two instances of the same item, you
// add the quantities together.
public void add(ShoppingCartItem otherItem)
{
this.quantity = this.quantity + otherItem.quantity;
}
// The subtract method is similar to the add method, but it
// removes a certain quantity of items.
public void subtract(ShoppingCartItem otherItem)
{
this.quantity = this.quantity - otherItem.quantity;
}
// You can store items in a hash table if you implement hashCode. It's
// always a good idea to do this.
public int hashCode()
{
return itemName.hashCode() + itemCost;
}
// The equals method does something a little dirty here, it only
// compares the item names and item costs. Technically, this is
// not the way that equals was intended to work.
public boolean equals(Object other)
{
if (this == other) return true;
if (!(other instanceof ShoppingCartItem))
return false;
ShoppingCartItem otherItem =
(ShoppingCartItem) other;
return (itemName.equals(otherItem
(itemCost == otherItem.itemCost);
}
// Create a copy of this object
public ShoppingCartItem copy()
{
return new ShoppingCartItem(itemName,
quantity, descriptionURL);
}
// Create a printable version of this object
public String toString()
{
return itemName+" cost: "+itemCost+" qty: "+quantity+" desc: "+
descriptionURL;
}
}
class ShoppingCartEvent
{
// Define the kinds of changes that can take place
public static final int ADDED_ITEM = 1;
public static final int REMOVED_ITEM = 2;
public static final int CHANGED_ITEM = 3;
// item is the item that is affected
public ShoppingCartItem item;
// eventType is the kind of change that has taken
// place (add/remove/change)
public int eventType;
public ShoppingCartEvent()
{
}
public ShoppingCartEvent(Shopping
int eventType)
{
this.item = item;
this.eventType = eventType;
}
}
// This class is a simple container of shopping cart items.
// It is observable, which means that it notifies any interested
// classes whenever it changes.
class ShoppingCart extends Observable
{
protected Vector items; // the items in the cart
protected int total; // the total item cost so far
public ShoppingCart()
{
items = new Vector();
total = 0;
}
// Add a new item and update the total
public void addItem(ShoppingCartItem newItem)
{
// See if there's already an item like this in the cart
int currIndex = items.indexOf(newItem);
ShoppingCartEvent event = new ShoppingCartEvent();
if (currIndex == -1) {
// If the item is new, add it to the cart
items.addElement(newItem);
event.item = newItem;
event.eventType = ShoppingCartEvent.ADDED_IT
} else {
// If there is a similar item, just add the quantities
ShoppingCartItem currItem =
(ShoppingCartItem)
items.elementAt(currIndex)
currItem.add(newItem);
event.item = currItem;
event.eventType = ShoppingCartEvent.CHANGED_
}
total += newItem.itemCost * newItem.quantity;
// Tell the observers what just happened
setChanged();
notifyObservers(event);
}
// Remove item removes an item from the cart. Since it removes
// n items from the cart at a time, if there are more than n items
// in the cart, it just subtracts n from the quantity.
public void removeItem(ShoppingCartIte
{
// Find this object in the cart
int currIndex = items.indexOf(oldItem);
ShoppingCartEvent event = new ShoppingCartEvent();
if (currIndex == -1) {
// If it wasn't there, just return, assume everything's okay
return;
} else {
ShoppingCartItem currItem =
(ShoppingCartItem)
items.elementAt(currIndex)
// If you are trying to subtract more items than are in the cart,
// adjust the amount you want to subtract so it is equal to the
// number of items in the cart.
if (oldItem.quantity > currItem.quantity) {
oldItem.quantity = currItem.quantity;
}
// Adjust the total
total -= oldItem.itemCost * oldItem.quantity;
currItem.subtract(oldItem)
event.item = currItem;
event.eventType = ShoppingCartEvent.CHANGED_
// If the quantity drops to 0, remove the item entirely
if (currItem.quantity == 0) {
items.removeElementAt(curr
event.eventType =
ShoppingCartEvent.REMOVED_
}
}
// Tell everyone what happened
setChanged();
notifyObservers(event);
}
// getItems returns a copy of all the items in the cart
public ShoppingCartItem[] getItems()
{
ShoppingCartItem[] itemArray =
new ShoppingCartItem[items.siz
items.copyInto(itemArray);
return itemArray;
}
}
// This class is a special version of a scrollable list that
// associates an object with each element in the list.
class ObjectList extends java.awt.List
{
Vector objects; // the objects that correspond to list entries
public ObjectList()
{
objects = new Vector();
}
public ObjectList(int items, boolean multiSelect)
{
super(items, multiSelect);
objects = new Vector();
}
public synchronized void addObject(Object ob)
{
// add a string version of the object to the list
super.addItem(ob.toString(
// add the object itself to the object vector
objects.addElement(ob);
}
public synchronized void addObject(Object ob, int position)
{
// add a string version of the object to the list
super.addItem(ob.toString(
// add the object itself to the object vector
if (position >= objects.size()) {
objects.addElement(ob);
} else {
objects.insertElementAt(ob
position);
}
}
public synchronized void addObject(String label, Object ob)
{
// Allow the object to be assigned a label independently of the object
super.addItem(label);
objects.addElement(ob);
}
public synchronized void addObject(String label, Object ob,
int position)
{
// Allow the object to be assigned a label independently of the object
super.addItem(label, position);
if (position >= objects.size()) {
objects.addElement(ob);
} else {
objects.insertElementAt(ob
position);
}
}
public synchronized void delObject(Object ob)
{
// See if the object is in the vector
int index = objects.indexOf(ob);
// If not, just return
if (index < 0) return;
// Remove the object from the vector
objects.removeElementAt(in
// Remove the list entry
super.delItem(index);
}
public synchronized Object getSelectedObject()
{
// Get the index of the current selection
int i = getSelectedIndex();
if (i == -1) return null;
// Return the object currently selected
return objects.elementAt(i);
}
public synchronized Object[] getSelectedObjects()
{
// Get the indices of all the selected objects
int[] selectedItems = getSelectedIndexes();
// Create an array of all the selected objects
Object[] whichObjects = new Object[
selectedItems.length];
for (int i=0; i < selectedItems.length; i++) {
whichObjects[i] = objects.elementAt(i);
}
return whichObjects;
}
public int indexOf(Object ob)
{
// Locate a particular object
return objects.indexOf(ob);
}
public Object objectAt(int index)
{
// Return the object at a particular index
return objects.elementAt(index);
}
public void replaceObject(Object ob, int index)
{
// Change a specific entry in the vector
replaceItem(ob.toString(),
// Change a specific entry in the list
objects.setElementAt(ob, index);
}
public void replaceObject(String label, Object ob, int index)
{
// Change a specific entry in the vector
replaceItem(label, index);
// Change a specific entry in the list
objects.setElementAt(ob, index);
}
}
// This class represents the catalog portion of a shopping cart.
// You can select items and then either view a description of
// the item or add the item to the shopping cart.
class ItemPickerApplet extends Applet implements Observer
{
ObjectList items;
ShoppingCart cart;
AppletRegistry registry;
public void init()
{
// Watch the applet registry to see when the Shopping Cart applet
// becomes active
registry = AppletRegistry.instance();
registry.addObserver(this)
items = new ObjectList();
// Get the URL of the list of items that are for sale
String itemURL = getParameter("itemList");
if (itemURL != null) fetchItems(itemURL);
// Put the items in the center of the screen
setLayout(new BorderLayout());
add("Center", items);
checkForShoppingCart();
// Add this applet to the registry
registry.addApplet("Item Picker", this);
}
public void checkForShoppingCart()
{
// See if the shopping cart has been loaded yet
Applet applet = registry.findApplet("Shopp
if (applet == null) return;
ShoppingCartApplet cartApplet = (ShoppingCartApplet)
applet;
// Get the shopping cart used by the shopping cart applet
cart = cartApplet.getShoppingCart
// Create the panel for adding items
Panel southPanel = new Panel();
// Set up some command buttons for adding and describing items
southPanel.add(new CommandButton("Describe Item",
new ItemPickerDescribe(this)))
southPanel.add(new CommandButton("Add Item",
new ItemPickerAdd(this)));
add("South", southPanel);
}
public void update(Observable obs, Object ob)
{
if (cart != null) return;
checkForShoppingCart();
}
// When someone presses the "Add Item" button, the doAdd method
// is called.
public void doAdd()
{
// Find out what object was selected
Object ob = items.getSelectedObject();
if (ob == null) return;
// Add the item to the cart
cart.addItem(((ShoppingCar
}
// When someone presses "Describe Item", the doDescribe method
// is called.
public void doDescribe()
{
// Find out which object was selected
Object ob = items.getSelectedObject();
if (ob == null) return;
ShoppingCartItem item = (ShoppingCartItem) ob;
// If it has a description URL, open it up in another frame
if (item.descriptionURL != null) {
getAppletContext().showDoc
item.descriptionURL, "descframe");
}
}
// parseItem extracts an item name, cost, and URL from a string. The
// items should be separated by |'s.
public void parseItem(String str)
{
StringTokenizer tokenizer = new StringTokenizer(str, "|");
if (tokenizer.countTokens() < 3) return;
String name = tokenizer.nextToken();
int cost = 0;
try {
cost = Integer.parseInt(tokenizer
} catch (Exception ignore) {
}
URL descURL = null;
try {
descURL = new URL(tokenizer.nextToken())
} catch (Exception ignore) {
}
items.addObject(name,
new ShoppingCartItem(name, cost, 1, descURL));
}
// fetchItems gets a list of available items from the web server and
// uses parseItem to parse the individual items. If a line begins with
// the # character, it is ignored (# is typically a comment character).
public void fetchItems(String urlName)
{
try {
URL url = new URL(urlName);
DataInputStream inStream =
new DataInputStream(
url.openStream());
String line;
while ((line = inStream.readLine()) != null) {
if (line.charAt(0) == '#') continue;
parseItem(line);
}
} catch (Exception e) {
}
}
}
class ItemPickerDescribe extends Object implements Command
{
ItemPickerApplet cart;
public ItemPickerDescribe(ItemPic
{
this.cart = cart;
}
public void doCommand()
{
cart.doDescribe();
}
}
// This class implements an applet registry where applets
// can locate each other. It is an observable, so if you want
// to wait for a particular class, you can be an observer. This
// is better than the polling you have to do with getApplet.
//
// This class is implemented as a singleton, which means there
// is only one. The single instance is kept in a protected
// static variable and returned by the instance() method.
class AppletRegistry extends Observable
{
// The single copy of the registry
protected static AppletRegistry registry;
// The table of applets
protected Hashtable applets;
// Used for generating unique applet names
protected int nextUnique;
protected AppletRegistry()
{
applets = new Hashtable();
nextUnique = 0;
}
// Returns the long instance of the registry. If there isn't a registry
// yet, it creates one.
public synchronized static AppletRegistry instance()
{
if (registry == null) {
registry = new AppletRegistry();
}
return registry;
}
// Adds a new applet to the registry - stores it in the table and
// sends a notification to its observers.
public synchronized void addApplet(String name, Applet newApplet)
{
applets.put(name, newApplet);
setChanged();
notifyObservers(new AppletRegistryEvent(
AppletRegistryEvent.ADD_AP
name, newApplet));
}
// Adds a new applet to the registry - stores it in the table and
// sends a notification to its observers. If uniqueName is false, the
// applet's name is non-unique. Store the applet in a table with a
// unique version of the name (appends <#> to the name where # is
// a constantly increasing number).
public synchronized void addApplet(String name, Applet newApplet,
boolean uniqueName)
{
if (!uniqueName && (applets.get(name) != null)) {
name = name + "<"+nextUnique+">";
nextUnique++;
}
applets.put(name, newApplet);
setChanged();
notifyObservers(new AppletRegistryEvent(
AppletRegistryEvent.ADD_AP
name, newApplet));
}
// removes an applet from the table and notifies the observers
public synchronized void removeApplet(Applet applet)
{
Enumeration e = applets.keys();
while (e.hasMoreElements()) {
Object key = e.nextElement();
if (applets.get(key) == applet) {
applets.remove(key);
setChanged();
notifyObservers(new AppletRegistryEvent(
AppletRegistryEvent.REMOVE
(String)key, applet));
return;
}
}
}
// removes an applet from the table and notifies the observers
public synchronized void removeApplet(String name)
{
Applet applet = (Applet) applets.get(name);
if (applet == null) return;
applets.remove(name);
setChanged();
notifyObservers(new AppletRegistryEvent(
AppletRegistryEvent.REMOVE
name, applet));
}
// finds an applet by name, or returns null if not found
public Applet findApplet(String name)
{
return (Applet) applets.get(name);
}
// lets you see all the applets in the registry
public Enumeration getApplets()
{
return applets.elements();
}
}
interface Command
{
public void doCommand();
}
// This class implements a Button that supports the
// Command interface. When the button is pressed, it
// invokes the doCommand method in the Command interface.
class CommandButton extends Button
{
// The interface where we will invoke doCommand
protected Command buttonCommand;
// It's always polite to implement the empty constructor if
// you can get away with it.
public CommandButton()
{
}
// Allow a CommandButton with a command but no label
public CommandButton(Command command)
{
buttonCommand = command;
}
// Allow a CommandButton to use the typical Button constructor
public CommandButton(String label)
{
super(label);
}
// The most useful constructor allows a label and a command
public CommandButton(String label, Command command)
{
super(label);
buttonCommand = command;
}
// When we get an action event, invoke doCommand in buttonCommand
public boolean action(Event evt, Object which)
{
// Make sure the action event is for this object
if (evt.target != this) return false;
// Make sure we have a buttonCommand defined!
if (buttonCommand == null) return false;
buttonCommand.doCommand();
return true;
}
// Since you can create a CommandButton without passing it a
// Command interface, you need to be able to set the command later.
public void setCommand(Command command)
{
buttonCommand = command;
}
}
// This applet shows you how to open up a socket to an HTTP server
// and post data to a server. It posts information to one of the
// example CGI programs set up by the NCSA.
class PostSockURL extends Object
{
static String post(URL a,String e){return "";} //who knows what this maniac is on about????
public static void main(String args[])
{
try {
// Open up a socket to the Web server where this applet came from
Socket sock = new Socket("hoohoo.ncsa.uiuc.e
// Get input and output streams for the socket connection
DataInputStream inStream = new DataInputStream(
sock.getInputStream());
DataOutputStream outStream = new DataOutputStream(
sock.getOutputStream());
// This request is what is sent by the NCSA's example form
String request = "button=on\r\n";
// Send the POST request to the server
// The request is of the form: POST filename HTTP/1.0
outStream.writeBytes("POST
" HTTP/1.0\r\n");
// Next, send the content type (don't forget the \r\n)
outStream.writeBytes(
"Content-type: application/octet-stream\r
// Send the length of the request
outStream.writeBytes(
"Content-length: "+request.length()+"\r\n")
// Send a \r\n to indicate the end of the header
outStream.writeBytes("\r\n
// Now send the information you are posting
outStream.writeBytes(reque
// Dump the response to System.out
int ch;
while ((ch = inStream.read()) >= 0) {
System.out.print((char) ch);
}
// We're done with the streams, so close them
inStream.close();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//some bullshit class I made up to get the program to compile
class ItemPickerAdd{
ItemPickerAdd(Object e){}
}
ASKER
wow.. appreciate the overwhelming response from all, managed to eliminate the errors caused by CommandButton(thanx zzynx). But the PostSockURL error still remains... anyway, i think the ShoppingCartOrder and ShoppingCartRemove is missing.. any ideas anyone???
ASKER
to SaMuEl: hmm, does it mean that if i throw in ur codes and compile, it should be error free? :)
> But the PostSockURL error still remains... anyway
I posted above where to find that class:
http://www.wutka.com/hackingjava/ch6.htm
I posted above where to find that class:
http://www.wutka.com/hackingjava/ch6.htm
Unfortunately not.
I gave up on getting the damn thing to compile.
Too much missing!
I gave up on getting the damn thing to compile.
Too much missing!
>> i think the ShoppingCartOrder and ShoppingCartRemove is missing.. any ideas anyone???
Just browse around at http://www.wutka.com/hackingjava/index.htm
Just browse around at http://www.wutka.com/hackingjava/index.htm
Here is the code - compiled and with source. Warnings
a. I've had to simulate two classes - check the ones that implement Command
b. One of the major classes (PostSockURL) has not been implemented properly (at least in the code found). This won't be difficult to do
http://www.cehjohnson.uklinux.net/aire/shop-cart-applet.jar
a. I've had to simulate two classes - check the ones that implement Command
b. One of the major classes (PostSockURL) has not been implemented properly (at least in the code found). This won't be difficult to do
http://www.cehjohnson.uklinux.net/aire/shop-cart-applet.jar
ASKER
thanks peeps.. for all ur pointer.. think i will need to get hold of the cd in the book to check out the missing classes. Many thanks, once again!
8-)
(although i would have thought assembling and compiling that code for you would possibly worth more than a C ;-))
(although i would have thought assembling and compiling that code for you would possibly worth more than a C ;-))
>>
think i will need to get hold of the cd in the book to check out the missing classes. Many thanks, once again!
>>
Ah that explains it - perhaps you missed my last-but-one comment?
think i will need to get hold of the cd in the book to check out the missing classes. Many thanks, once again!
>>
Ah that explains it - perhaps you missed my last-but-one comment?
>> although i would have thought assembling and compiling that code for you would possibly worth more than a C
Agree.
QLJ, did you know that
- giving an A grade doesn't cost you any more points then a C-grade?
- we get the points x2, x3 or x4 if you give a C, B or A grade?
Agree.
QLJ, did you know that
- giving an A grade doesn't cost you any more points then a C-grade?
- we get the points x2, x3 or x4 if you give a C, B or A grade?