File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes Some help. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Some help." Watch "Some help." New topic
Author

Some help.

jimmy siljanovski
Greenhorn

Joined: May 24, 2006
Posts: 1
Can someone help me with this code. The stock tracker is supposed to start the grapher when numbers are entered.

Stock Tracker code:

/**
* StockTracker.java
*
* StockTracker Application built with AWT components
*
* The Stock Tracker charts the price movements of a particular
* ASX share after the user enters the ASX code, buying price and
* the quantity purchased. The user can start the tracker with the
* BUY button. The tracker plots a graph based on generating random
* prices and simultaneously displays status information such as
* running totals of profit and prices. The user can buy, sell suspend
* and resume the trading of their shares. The user can trigger a
* status report displaying details of their purchase and profit at
* any point in time.
* @author Stefan Batsas
* @version 1.00 2005-08-30
*
*/


import java.awt.*;
import java.text.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import static java.awt.event.KeyEvent.*;

public class StockTracker extends Frame implements
ActionListener, ItemListener, KeyListener {

/** The share ASX code */
private String asxcode;

/** The share price when bought */
private double buyPrice;

/** The share price when sold */
private double sellPrice;

/** quantity of shares */
private int quantity;

/** profit */
private double profit;

/** flag for status of grapher */
private boolean isGrapherPlotting;

/** Decimal formatter */
private DecimalFormat df;

/** Combo box to select stock code */
private Choice cbStockCodes;

/** Field to enter buying price of share */
private TextField txtPrice;

/** Field to enter quantity of shares purchased */
private TextField txtQuantity;

/** Button to start tracking the stock - signals shares are bought */
private Button btnBuy;

/** Button to stop tracking the stock - signals shares are sold */
private Button btnSell;

/** Button to suspend tracking the stock and check profit */
private Button btnSuspend;

/** Button to resume tracking the stock */
private Button btnResume;

/** Button to reset the applet and start over */
private Button btnReset;

/** Data label that displays the current market price */
private Label lblCurrentPrice;

/** Data Label that displays the Stock Name */
private Label lblStockName;

/** Data label that displays the current profit */
private Label lblProfit;

//------------------------------
/** declare grapher object */
//------------------------------

/** Timer thread that calls repaint on the tracker panel */
private Timer timer;


/**
* StockTracker constructor method
*/

public StockTracker() {


setSize(500,250);
setTitle("Stock Tracker");

// component initialisation hidden away in this method
initComponents();


// initialise north panel
Panel pnlNorth = new Panel(new BorderLayout());
//pnlNorth.setBorder(BorderFactory.createRaisedBevelBorder());
pnlNorth.setBackground(Color.ORANGE);



// initialise west panel
Panel pnlWest = new Panel(new GridLayout(5,2,10,10));
//pnlWest.setBorder(BorderFactory.createRaisedBevelBorder());

// initialise center panel
Panel pnlCenter = new Panel(new BorderLayout());
//pnlCenter.setBorder(BorderFactory.createLoweredBevelBorder());


// initialise south panel
Panel pnlSouth = new Panel(new GridLayout(1,9,5,5));
pnlSouth.setBackground(Color.CYAN);
pnlSouth.setFont(new Font("arial",Font.BOLD,16));

// add component to north panel
Label lblTitle = new Label("Stock Tracker",Label.CENTER);
lblTitle.setFont(new Font("arial",Font.BOLD, 36));
pnlNorth.add(lblTitle);



// add components to west panel
pnlWest.add(new Label("Select Code",Label.CENTER));
pnlWest.add(cbStockCodes);
pnlWest.add(new Label("Enter Price",Label.CENTER));
pnlWest.add(txtPrice);
pnlWest.add(new Label("Enter Quantity",Label.CENTER));
pnlWest.add(txtQuantity);
pnlWest.add(btnBuy);
pnlWest.add(btnSell);
pnlWest.add(btnSuspend);
pnlWest.add(btnResume);

//------------------------------
// add grapher to center panel |
//------------------------------


// add components to south panel
pnlSouth.add(new Label("Share:"));
pnlSouth.add(lblStockName);
pnlSouth.add(new Label("Price:"));
pnlSouth.add(lblCurrentPrice);
pnlSouth.add(new Label("Profit:"));
pnlSouth.add(lblProfit);
pnlSouth.add(btnReset);


// add panels to frame
add(pnlNorth, BorderLayout.NORTH);
add(pnlWest, BorderLayout.WEST);
add(pnlCenter, BorderLayout.CENTER);
add(pnlSouth, BorderLayout.SOUTH);

setVisible(true);

} // constructor


/**
* Implement ActionListener interface
*
* respond to button clicks which drive the tracker
* Buy button - starts graph and tracker
* Sell button - stops graph and displays status report
* Resume button - restarts graph and tracker
* Suspend button - only stops graph
* reset button - clears and resets all objects
*
*
*/

public void actionPerformed(ActionEvent e){



if(e.getSource() == btnBuy){


if(!isGrapherPlotting){

if(isDigits(txtQuantity.getText())
&& isNumeric(txtPrice.getText())){


quantity = Integer.parseInt(txtQuantity.getText());
buyPrice = Double.parseDouble(txtPrice.getText());

//-------------------------------------
// set price of grapher with buyPrice |
//-------------------------------------
//----------------
// start grapher |
//----------------


timer.start();
isGrapherPlotting = true;

}
}

} else if(e.getSource() == btnSell){

if(isGrapherPlotting){

//----------------
// stop grapher |
//----------------


timer.stop();
displayStatus();
isGrapherPlotting = false;

}

}else if(e.getSource() == btnSuspend){
if(isGrapherPlotting){

//----------------
// stop grapher |
//----------------

timer.stop();
isGrapherPlotting = false;
}

} else if(e.getSource() == btnResume){
if(!isGrapherPlotting){

//----------------
// resume grapher|
//----------------

timer.restart();
isGrapherPlotting = true;
}

} else if(e.getSource() == btnReset){

reset();

} // end if



} // actionPerformed

/**
* Convenience method for displaying message dialog
*
*/

public void displayError(String message){

JOptionPane.showMessageDialog(this, message, "Validation Message",
JOptionPane.ERROR_MESSAGE);


} // displayError


/**
* Diplay current share status
*
*/
public void displayStatus(){

//-----------------------------------------------
// get grapher price and assign to sellPrice |
//-----------------------------------------------


profit = (sellPrice - buyPrice) * quantity;
StringBuffer sb = new StringBuffer();

sb.append("Share: ").append(asxcode).append("\n");
sb.append("Bought: ").append(quantity).append(" @ ");
sb.append(df.format(buyPrice)).append("\n");
sb.append("Sold: ").append(quantity).append(" @ ");

sb.append(df.format(sellPrice)).append("\n");
sb.append("Profit: ").append(df.format(profit));


JOptionPane.showMessageDialog(null,sb.toString(),"Stock Tracker - Profit Report",
JOptionPane.INFORMATION_MESSAGE);
} // displayStatus





/**
* Hides intialisation of declared variables and components
*
*/
public void initComponents(){

// initialise currency formatter
df = new DecimalFormat("$0.00");


// build combo
cbStockCodes = new Choice();
cbStockCodes.addItem("AMP");
cbStockCodes.addItem("BHP");
cbStockCodes.addItem("CSL");
cbStockCodes.addItem("TLS");
cbStockCodes.addItemListener(this);

// initialise price field
txtPrice = new TextField(5);
//txtPrice.setHorizontalAlignment(TextField.RIGHT);
txtPrice.addKeyListener(this);

// initialise quantity field
txtQuantity = new TextField(5);
//txtQuantity.setHorizontalAlignment(TextField.RIGHT);
txtQuantity.addKeyListener(this);


// initialise buy button
btnBuy = new Button("Buy");
btnBuy.addActionListener(this);

// initialise sell button
btnSell = new Button("Sell");
btnSell.addActionListener(this);

// initialise suspend button
btnSuspend = new Button("Suspend");
btnSuspend.addActionListener(this);


btnResume = new Button("Resume");
btnResume.addActionListener(this);


// initialise reset button
btnReset = new Button("Reset");
btnReset.addActionListener(this);

// initialise current price label
lblCurrentPrice = new Label("0.00");
lblCurrentPrice.setForeground(Color.RED);


// initialise profit label
lblProfit = new Label("0.00");
lblProfit.setForeground(Color.RED);

// initialise stock name label
lblStockName = new Label(" ");
lblStockName.setForeground(Color.RED);

//-------------------------------------------
// initialise grapher |
// set the seed of grapher to 0.5 |
//-------------------------------------------


/**
* initialise timer that controls status info
* Anonymous ActionListener created as argument
*/

timer = new Timer( 100,new ActionListener(){

public void actionPerformed(ActionEvent e){


double price = 0;

// --------------------------------------------
// get price from grapher and assign to price |
// --------------------------------------------


double profit = (price - buyPrice)* quantity;

lblCurrentPrice.setText(df.format(price));
lblProfit.setText(df.format(profit));

}

});


} // initComponents



/**
* Validation method for integer input
* @param s - the string value to be validated
* @return - true (valid) or false (not valid)
*/

public boolean isDigits(String s){

try{

int value = Integer.parseInt(s);
return true;

}catch(NumberFormatException e){
return false;
}
} // isDigits


/**
* Validation method for decimal input
* @param s - the string value to be validated
* @return - true (valid) or false (not valid)
*/

public boolean isNumeric(String s){

try{

double value = Double.parseDouble(s);
return true;

}catch(NumberFormatException e){
return false;
}
} // isNumeric


/**
* Implementing ItemListener interface
* for Choice component. Choice component does not fire action events
* respond to Choice selection to set asx stock code
*/
public void itemStateChanged(ItemEvent e){
asxcode = (String)((Choice)e.getSource()).getSelectedItem();

lblStockName.setText(asxcode);
cbStockCodes.transferFocus();

}





/**
* Implement the KeyListener Interface
* Input Validation Implementation
*
* Respond to keypress events - non numerical keys
* invoke message dialog.
*
*/

public void keyPressed(KeyEvent e){


// Get the unicode value
int key = e.getKeyCode();

if(key == VK_ENTER||key == VK_DOWN){ // Constants available via static import
// Enter key moves cursor to next field
((TextField)e.getSource()).transferFocus();

}else if( key == VK_BACK_SPACE ||
key == VK_SPACE ||
key == VK_DELETE ||
key == VK_LEFT ||
key == VK_RIGHT){
// ignore space, back-space,delete key and decimal points

return;

} else if(key == VK_PERIOD){

if(e.getSource() == txtPrice){
return;
}else{
displayError("Whole numbers only please");
txtQuantity.selectAll();

}
} else if(key < VK_0 || key > VK_9 ){
// not a digit
displayError("Enter numerical values");
((TextField)e.getSource()).selectAll();

} // if

} // keyPressed

// not needed
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}

/*
* Clear state, Reset fields, timer threads, grapher
*/
public void reset(){


//---------------------------------------------
// reset grapher |
// set grapher seed to 0.5 |
//---------------------------------------------


timer.stop();
asxcode = "";
buyPrice = 0.0;
quantity = 0;
sellPrice = 0.0;
profit = 0.0;
lblStockName.setText(" ");
lblCurrentPrice.setText("0.00");
lblProfit.setText("0.00");
txtPrice.setText("");
txtQuantity.setText("");
isGrapherPlotting = false;
cbStockCodes.requestFocus();


} // reset

public static void main(String[] args){

StockTracker st = new StockTracker();
}

} // StockTracker

Grapher code:

/**
* Grapher.java
*
*The Grapher class is a Java Canvas component; The Canvas class
* is a suitable component for drawing or rendering graphics. It will
* be used to plot the share price graph. The Grapher should plot the
* share price using a random price generator, store the initial buy price,
* the current price and calculate the current profit as the graph is plotted.
* The graph animation should be controlled with a timer thread that can
* be started, stopped and restarted.
*
*
* @author Stefan Batsas
* @version 1.00 2005-08-30
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Grapher extends Canvas implements ActionListener {


/** Timer thread that calls repaint to plot stock price graph */
private Timer timer;

/** The current share price */
private double price;

/** x co-ordinate denotes period in time to graph */
private int xpos;

/** y co-ordinate denotes current price to graph */
private int ypos;

/**
* delta is
Martin Simons
Ranch Hand

Joined: Mar 02, 2006
Posts: 196
That's a lot of code without any real question being posted with it.

What, exactly, is your question/problem? Are you getting an exception?
Are you confused how to open a specific Panel/Frame?
jimmy siljanoski
Greenhorn

Joined: May 28, 2006
Posts: 4
This is the grapher code:

/**
* Grapher.java
*
*The Grapher class is a Java Canvas component; The Canvas class
* is a suitable component for drawing or rendering graphics. It will
* be used to plot the share price graph. The Grapher should plot the
* share price using a random price generator, store the initial buy price,
* the current price and calculate the current profit as the graph is plotted.
* The graph animation should be controlled with a timer thread that can
* be started, stopped and restarted.
*
*
* @author Stefan Batsas
* @version 1.00 2005-08-30
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Grapher extends Canvas implements ActionListener {


/** Timer thread that calls repaint to plot stock price graph */
private Timer timer;

/** The current share price */
private double price;

/** x co-ordinate denotes period in time to graph */
private int xpos;

/** y co-ordinate denotes current price to graph */
private int ypos;

/**
* delta is number of pixel increment/decrement for each 1 cent
* of price move - default = 1
*/
private int delta = 1;

/** Seed for random engine */
private double seed;

/**
* Constructor
*
*/
public Grapher() {

this.setBackground(Color.WHITE);
this.setForeground(Color.BLUE);
timer = new Timer(100, this);
setStartXY(0,100);
repaint();

} // init

/**
* paint the price dot on the canvas
*/

public void paint(Graphics g) {
g.drawOval(xpos,ypos,3,3);

} // paint

/**
* override update to retain the plotted graph
*/
public void update(Graphics g){

paint(g);

} // update

/**
* Generate random price - set price and x,y
*/

public void actionPerformed(ActionEvent e){

// increment graph along x-axis each timer tick
xpos++;

// Number greater than seed moves price down
// and vice verse
if(Math.random() > seed){
ypos+=delta;
price -= 0.01;
}else{
ypos-=delta;
price += 0.01;
}

// alter seed
seed = Math.random();

// plot graph vertice
repaint();

} // actionPerformed


/**
* Starts the grapher thread
*/
public void start(){

timer.start();

} // start

/**
* Stops the grapher thread
*/

public void stop(){

timer.stop();

} // stop

/**
* Restarts the grapher thread
*/
public void resume(){

timer.restart();

} // resume


/**
* Reset - clears canvas and resets field state
*
*/
public void reset(){

timer.stop();
Graphics g = getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,0,this.getSize().width, this.getSize().height);
g.setColor(Color.BLUE);
setPrice(0.0);
setSeed(0.0);
setStartXY(0,100);

} // reset

/**
* @return current price
*
*/
public double getPrice(){

return price;

} // getPrice

/**
* @param price
* sets the current price
*
*/
public void setPrice(double price){

this.price = price;

} // setBuyPrice

/**
* @param seed
* sets the seed value at start
*/
public void setSeed(double seed){

this.seed = seed;

} // setSeed

/**
* @param x, y coordinates
* sets the x and y coordinates where graph begins on canvas
*/
public void setStartXY(int x, int y){
xpos = x;
ypos = y;

} // setStart

/**
* @param delta - the y change in pixels
*
*/
public void setDelta(int delta){
this.delta = delta;
}


} // Grapher

I'm supposed to create a stock tracker program. Most of the code is there all that has to be done is be modified. The modification points are where the comments are placed telling you what to do. Hope it makes it a little clearer. Your help will be much appreciated.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi,

Welcome to JavaRanch!

We don't do homework for people -- we help them learn to do their own. If I see someone posting homework answers, I will actually delete the posts. Now, if you have a specific question about Java, we'll be happy to answer it or help you to find the answer. But "Some help" isn't a question and we won't try to answer it.


[Jess in Action][AskingGoodQuestions]
jimmy siljanoski
Greenhorn

Joined: May 28, 2006
Posts: 4
Its not my homework. My mate gave me this code because they are making him do some java in his IT course for no reason. All he wants to do is pass it not excel at it because he will never use it again.

If you cant help than maybe you can answer these questions:

What is object oriented programming?
Where do you place definitions for data fields in a class?
Why are radio buttons added to a button group?
What is a java interface?
Definitions of private and public?
Which object created at runtime is responsible for rendering your Frame object?
What class would you use to display a Message Dialog Box for YES or NO confirmation?
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
> All he wants to do is pass it not excel at it because he will never use it again.

I hope he fails...

at everything he does.
jimmy siljanoski
Greenhorn

Joined: May 28, 2006
Posts: 4
All i wanted was some help but it appears that people here are unnecessarily rude and arrogant.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42929
    
  68
It doesn't matter much whether it's your homework or your buddys - what Ernest said still aplies. And it's not a very appealing proposition to try to help someone who doesn't want to learn, just get it over with.

You're right that Michaels comment is certainly borderline in regard to the "Be Nice" rule.
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
> You're right that Michaels comment is certainly borderline in regard to the "Be Nice" rule.

nice to fellow ranchers, no probs

nice to those who are even too lazy to post their own request for a handout - never..... :-)
jimmy siljanoski
Greenhorn

Joined: May 28, 2006
Posts: 4
/**
* StockTracker.java
*
* StockTracker Application built with AWT components
*
* The Stock Tracker charts the price movements of a particular
* ASX share after the user enters the ASX code, buying price and
* the quantity purchased. The user can start the tracker with the
* BUY button. The tracker plots a graph based on generating random
* prices and simultaneously displays status information such as
* running totals of profit and prices. The user can buy, sell suspend
* and resume the trading of their shares. The user can trigger a
* status report displaying details of their purchase and profit at
* any point in time.
* @author Stefan Batsas
* @version 1.00 2005-08-30
*
*/


import java.awt.*;
import java.text.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import static java.awt.event.KeyEvent.*;

public class StockTracker extends JApplet implements
ActionListener, ItemListener, KeyListener {

/** The share ASX code */
private String asxcode;

/** The share price when bought */
private double buyPrice;

/** The share price when sold */
private double sellPrice;

/** quantity of shares */
private int quantity;

/** profit */
private double profit;

/** flag for status of grapher */
private boolean isGrapherPlotting;

/** Decimal formatter */
private DecimalFormat df;

/** Combo box to select stock code */
private JComboBox cbStockCodes;

/** Field to enter buying price of share */
private JTextField txtPrice;

/** Field to enter quantity of shares purchased */
private JTextField txtQuantity;

/** JButton to start tracking the stock - signals shares are bought */
private JButton btnBuy;

/** JButton to stop tracking the stock - signals shares are sold */
private JButton btnSell;

/** JButton to suspend tracking the stock and check profit */
private JButton btnSuspend;

/** JButton to resume tracking the stock */
private JButton btnResume;

/** JButton to reset the applet and start over */
private JButton btnReset;

/** Data label that displays the current market price */
private JLabel lblCurrentPrice;

/** Data JLabel that displays the Stock Name */
private JLabel lblStockName;

/** Data label that displays the current profit */
private JLabel lblProfit;

//------------------------------
/** declare grapher object */
//------------------------------

private Grapher grapher;


/** Timer thread that calls repaint on the tracker panel */
private Timer timer;


/**
* StockTracker constructor method
*/

public void init() {




// component initialisation hidden away in this method
initComponents();


// initialise north panel
JPanel pnlNorth = new JPanel(new BorderLayout());
//pnlNorth.setBorder(BorderFactory.createRaisedBevelBorder());
pnlNorth.setBackground(Color.ORANGE);



// initialise west panel
JPanel pnlWest = new JPanel(new GridLayout(5,2,10,10));
//pnlWest.setBorder(BorderFactory.createRaisedBevelBorder());

// initialise center panel
JPanel pnlCenter = new JPanel(new BorderLayout());
//pnlCenter.setBorder(BorderFactory.createLoweredBevelBorder());


// initialise south panel
JPanel pnlSouth = new JPanel(new GridLayout(1,9,5,5));
pnlSouth.setBackground(Color.CYAN);
pnlSouth.setFont(new Font("arial",Font.BOLD,16));

// add component to north panel
JLabel lblTitle = new JLabel("Stock Tracker",JLabel.CENTER);
lblTitle.setFont(new Font("arial",Font.BOLD, 36));
pnlNorth.add(lblTitle);



// add components to west panel
pnlWest.add(new JLabel("Select Code",JLabel.CENTER));
pnlWest.add(cbStockCodes);
pnlWest.add(new JLabel("Enter Price",JLabel.CENTER));
pnlWest.add(txtPrice);
pnlWest.add(new JLabel("Enter Quantity",JLabel.CENTER));
pnlWest.add(txtQuantity);
pnlWest.add(btnBuy);
pnlWest.add(btnSell);
pnlWest.add(btnSuspend);
pnlWest.add(btnResume);

//------------------------------
// add grapher to center panel |
//------------------------------

pnlCenter.add(grapher);


// add components to south panel
pnlSouth.add(new JLabel("Share:"));
pnlSouth.add(lblStockName);
pnlSouth.add(new JLabel("Price:"));
pnlSouth.add(lblCurrentPrice);
pnlSouth.add(new JLabel("Profit:"));
pnlSouth.add(lblProfit);
pnlSouth.add(btnReset);


Container c = getContentPane();

// add panels to frame
c.add(pnlNorth, BorderLayout.NORTH);
c.add(pnlWest, BorderLayout.WEST);
c.add(pnlCenter, BorderLayout.CENTER);
c.add(pnlSouth, BorderLayout.SOUTH);





} // constructor


/**
* Implement ActionListener interface
*
* respond to button clicks which drive the tracker
* Buy button - starts graph and tracker
* Sell button - stops graph and displays status report
* Resume button - restarts graph and tracker
* Suspend button - only stops graph
* reset button - clears and resets all objects
*
*
*/

public void actionPerformed(ActionEvent e){



if(e.getSource() == btnBuy){


if(!isGrapherPlotting){

if(isDigits(txtQuantity.getText())
&& isNumeric(txtPrice.getText())){


quantity = Integer.parseInt(txtQuantity.getText());
buyPrice = Double.parseDouble(txtPrice.getText());

//-------------------------------------
// set price of grapher with buyPrice |
//-------------------------------------

grapher.setPrice(buyPrice);


//----------------
// start grapher |
//----------------

grapher.start();


timer.start();
isGrapherPlotting = true;

}
}

} else if(e.getSource() == btnSell){

if(isGrapherPlotting){

//----------------
// stop grapher |
//----------------

grapher.stop();




timer.stop();
displayStatus();
isGrapherPlotting = false;

}

}else if(e.getSource() == btnSuspend){
if(isGrapherPlotting){

//----------------
// stop grapher |
//----------------

grapher.stop();

timer.stop();
isGrapherPlotting = false;
}

} else if(e.getSource() == btnResume){
if(!isGrapherPlotting){

//----------------
// resume grapher|
//----------------

grapher.resume();

timer.restart();
isGrapherPlotting = true;
}

} else if(e.getSource() == btnReset){

reset();

} // end if



} // actionPerformed

/**
* Convenience method for displaying message dialog
*
*/

public void displayError(String message){

JOptionPane.showMessageDialog(this, message, "Validation Message",
JOptionPane.ERROR_MESSAGE);


} // displayError


/**
* Diplay current share status
*
*/
public void displayStatus(){

//-----------------------------------------------
// get grapher price and assign to sellPrice |
//-----------------------------------------------

sellPrice = grapher.getPrice();


profit = (sellPrice - buyPrice) * quantity;
StringBuffer sb = new StringBuffer();

sb.append("Share: ").append(asxcode).append("\n");
sb.append("Bought: ").append(quantity).append(" @ ");
sb.append(df.format(buyPrice)).append("\n");
sb.append("Sold: ").append(quantity).append(" @ ");

sb.append(df.format(sellPrice)).append("\n");
sb.append("Profit: ").append(df.format(profit));


JOptionPane.showMessageDialog(null,sb.toString(),"Stock Tracker - Profit Report",
JOptionPane.INFORMATION_MESSAGE);
} // displayStatus





/**
* Hides intialisation of declared variables and components
*
*/
public void initComponents(){

// initialise currency formatter
df = new DecimalFormat("$0.00");


// build combo
cbStockCodes = new JComboBox();
cbStockCodes.addItem("AMP");
cbStockCodes.addItem("BHP");
cbStockCodes.addItem("CSL");
cbStockCodes.addItem("TLS");
cbStockCodes.addItemListener(this);

// initialise price field
txtPrice = new JTextField(5);
//txtPrice.setHorizontalAlignment(JTextField.RIGHT);
txtPrice.addKeyListener(this);

// initialise quantity field
txtQuantity = new JTextField(5);
//txtQuantity.setHorizontalAlignment(JTextField.RIGHT);
txtQuantity.addKeyListener(this);


// initialise buy button
btnBuy = new JButton("Buy");
btnBuy.addActionListener(this);

// initialise sell button
btnSell = new JButton("Sell");
btnSell.addActionListener(this);

// initialise suspend button
btnSuspend = new JButton("Suspend");
btnSuspend.addActionListener(this);


btnResume = new JButton("Resume");
btnResume.addActionListener(this);


// initialise reset button
btnReset = new JButton("Reset");
btnReset.addActionListener(this);

// initialise current price label
lblCurrentPrice = new JLabel("0.00");
lblCurrentPrice.setForeground(Color.RED);


// initialise profit label
lblProfit = new JLabel("0.00");
lblProfit.setForeground(Color.RED);

// initialise stock name label
lblStockName = new JLabel(" ");
lblStockName.setForeground(Color.RED);

//-------------------------------------------
// initialise grapher |
// set the seed of grapher to 0.5 |
//-------------------------------------------

grapher = new Grapher();
grapher.setSeed(0.5);


/**
* initialise timer that controls status info
* Anonymous ActionListener created as argument
*/

timer = new Timer( 100,new ActionListener(){

public void actionPerformed(ActionEvent e){


double price = 0;

// --------------------------------------------
// get price from grapher and assign to price |
// --------------------------------------------

price = grapher.getPrice();


double profit = (price - buyPrice)* quantity;

lblCurrentPrice.setText(df.format(price));
lblProfit.setText(df.format(profit));

}

});


} // initComponents



/**
* Validation method for integer input
* @param s - the string value to be validated
* @return - true (valid) or false (not valid)
*/

public boolean isDigits(String s){

try{

int value = Integer.parseInt(s);
return true;

}catch(NumberFormatException e){
return false;
}
} // isDigits


/**
* Validation method for decimal input
* @param s - the string value to be validated
* @return - true (valid) or false (not valid)
*/

public boolean isNumeric(String s){

try{

double value = Double.parseDouble(s);
return true;

}catch(NumberFormatException e){
return false;
}
} // isNumeric


/**
* Implementing ItemListener interface
* for JComboBox component. JComboBox component does not fire action events
* respond to JComboBox selection to set asx stock code
*/
public void itemStateChanged(ItemEvent e){
asxcode = (String)((JComboBox)e.getSource()).getSelectedItem();

lblStockName.setText(asxcode);
cbStockCodes.transferFocus();

}





/**
* Implement the KeyListener Interface
* Input Validation Implementation
*
* Respond to keypress events - non numerical keys
* invoke message dialog.
*
*/

public void keyPressed(KeyEvent e){


// Get the unicode value
int key = e.getKeyCode();

if(key == VK_ENTER||key == VK_DOWN){ // Constants available via static import
// Enter key moves cursor to next field
((JTextField)e.getSource()).transferFocus();

}else if( key == VK_BACK_SPACE ||
key == VK_SPACE ||
key == VK_DELETE ||
key == VK_LEFT ||
key == VK_RIGHT){
// ignore space, back-space,delete key and decimal points

return;

} else if(key == VK_PERIOD){

if(e.getSource() == txtPrice){
return;
}else{
displayError("Whole numbers only please");
txtQuantity.selectAll();

}
} else if(key < VK_0 || key > VK_9 ){
// not a digit
displayError("Enter numerical values");
((JTextField)e.getSource()).selectAll();

} // if

} // keyPressed

// not needed
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}

/*
* Clear state, Reset fields, timer threads, grapher
*/
public void reset(){


//---------------------------------------------
// reset grapher |
// set grapher seed to 0.5 |
//---------------------------------------------

grapher.reset();
grapher.setSeed(0.5);


timer.stop();
asxcode = "";
buyPrice = 0.0;
quantity = 0;
sellPrice = 0.0;
profit = 0.0;
lblStockName.setText(" ");
lblCurrentPrice.setText("0.00");
lblProfit.setText("0.00");
txtPrice.setText("");
txtQuantity.setText("");
isGrapherPlotting = false;
cbStockCodes.requestFocus();


} // reset




} // StockTracker

Done.
Can someone answer those questions i asked previously.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Some help.