Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

using Java You are to write a GUI program that will allow a user to buy, sell an

ID: 3818897 • Letter: U

Question

using Java You are to write a GUI program that will allow a user to buy, sell and view stocks in a stock portfolio. This document will describe the minimum expected functions for a grade of 90. Your mission is to “go and do better.” The meaning of “do better” is largely up to you. For example, you might track the profit or loss on the trades. You might allow for sales of partial holdings, or subsequent purchases to be added to an existing holding. Be creative. Objectives By the end of this project, the student will be able to write a GUI program that maintains a cash balance, list of stock holdings, supports buying and selling of stocks and displays the current portfolio inventory demonstrate the ability to assemble already-written classes into a larger, more complicated program demonstrate the ability to segregate business logic from user interface code. Capabilities At a minimum, the program should allow a user to buy a stock with a given number of shares and price per share. display the current portfolio (stock ticker, number of shares, initial price). update the portfolio display for purchases and sales. allow the user to sell all of the shares of a given stock. give the user an initial cash balance, and update and display the balance according to the user's purchases and sales. ignore any transaction that causes the cash position to go below $0. Sample Execution The initial frame has text fields for the stock ticker, number of shares, and price per share. It has a label for the current cash balance. It also has “buy” and “sell” buttons. Let's buy Apple (ticker AAPL) shares. First we enter the ticker, number of shares and price per share. Then we click “Buy.” Note our cash was reduced accordingly. Our portfolio inventory now displays since it's no longer empty. Let's buy IBM. We enter the ticker, number of shares and price per share. We click “Buy.” Our cash is reduced appropriately, our portfolio is updated. WidgetView moves things around. We won't worry about that. We also won't worry about the not-quite-right truncation of the last penny of the cash balance. Let's buy Microsoft (MSFT). We'll just skip to the completed transaction.We click “Sell,” and the portfolio listing and cash are updated

Explanation / Answer

The following three classes(MarketSimulator, MarketTable ,MarketDataModel ) builds the GUI for stock market portfolio, where stock prices change dynamically:

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

public class MarketSimulator extends JFrame implements Runnable {

Stock[] market = {
new Stock("JTree", 14.57),
new Stock("JTable", 17.44),
new Stock("JList", 16.44),
new Stock("JButton", 7.21),
new Stock("JComponent", 27.40)
};
boolean monitor;
Random rg = new Random();
Thread runner;

public MarketSimulator () {
super("Thread only version . . .");
runner = new Thread(this);
runner.start();
}

// This version creates a real frame so that you can see how the typical
// stocks get updated.


public MarketSimulator (boolean monitorOn) {
super("Stock Market Monitor");
setSize(400, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
monitor = monitorOn;

getContentPane().add(new JLabel("Trading is active. " +
"Close this window to close the market."),
BorderLayout.CENTER);
runner = new Thread(this);
runner.start();
}

//In an infinite loop, just pick a
// random stock and update its price. To make the program interesting, we'll
// update a price every second.
public void run() {
while(true) {
int whichStock = Math.abs(rg.nextInt()) % market.length;
double delta = rg.nextDouble() - 0.4;
market[whichStock].update(delta);
if (monitor) {
market[whichStock].print();
}
try {
Thread.sleep(1000);
}
catch(InterruptedException ie) {
}
}
}

public Stock getQuote(int index) {
return market[index];
}

// This method returns the list of all the symbols in the market table
public String[] getSymbols() {
String[] symbols = new String[market.length];
for (int i = 0; i < market.length; i++) {
symbols[i] = market[i].symbol;
}
return symbols;
}

public static void main(String args[]) {
MarketSimulator myMarket = new MarketSimulator (args.length > 0);
myMarket.setVisible(true);
}
}

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

public class MarketTable extends JFrame {

public MarketTable() {
super("Dynamic Data Test");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);

// Set up our table model with a 5-second polling delay
MarketDataModel mdm = new MarketDataModel(5);

// Pick which stocks we want to watch . . .
mdm.setStocks(new int[] { 0, 1, 2 });

// And pop up the table
JTable jt = new JTable(mdm);
JScrollPane jsp = new JScrollPane(jt);
getContentPane().add(jsp, BorderLayout.CENTER);
}

public static void main(String args[]) {
MarketTable mt = new MarketTable();
mt.setVisible(true);
}
}

import javax.swing.table.*;
import javax.swing.*;

public class MarketDataModel extends AbstractTableModel
implements Runnable {

Thread runner;
MarketSimulator market;
int delay;

public MarketDataModel(int initialDelay) {
market = new MarketSimulator ();
delay = initialDelay * 1000;
Thread runner = new Thread(this);
runner.start();
}

Stock[] stocks = new Stock[0];
int[] stockIndices = new int[0];
String[] headers = {"Symbol", "Price", "Change", "Last updated"};

public int getRowCount() { return stocks.length; }
public int getColumnCount() { return headers.length; }

public String getColumnName(int c) { return headers[c]; }

public Object getValueAt(int r, int c) {
switch(c) {
case 0:
return stocks[r].symbol;
case 1:
return new Double(stocks[r].price);
case 2:
return new Double(stocks[r].delta);
case 3:
return stocks[r].lastUpdate;
}
throw new IllegalArgumentException("Bad cell (" + r + ", " + c +")");
}

public void setDelay(int seconds) { delay = seconds * 1000; }
public void setStocks(int[] indices) {
stockIndices = indices;
updateStocks();
fireTableDataChanged();
}

public void updateStocks() {
stocks = new Stock[stockIndices.length];
for (int i = 0; i < stocks.length; i++) {
stocks[i] = market.getQuote(stockIndices[i]);
}
}

public void run() {
while(true) {
// Blind update . . . we could check for real deltas if necessary
updateStocks();

// We know there are no new columns, so don't fire a data change, only
// fire a row update . . . this keeps the table from flashing
fireTableRowsUpdated(0, stocks.length - 1);
try { Thread.sleep(delay); }
catch(InterruptedException ie) {}
}
}
}

/**********************************************************************************************************************************/

The following class adds stock of three companies and provides the functionality of updating , buying stocks, and getting the entire portfolio value for the customer: