SlideShare a Scribd company logo
1 of 15
Download to read offline
You are to write a GUI program that will allow a user to buy, sell and view stocks in a stock
portfolio.
Objective:
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.
Program Capabilities:
1. Allow a user to buy a stock with a given number of shares and price per share.
2. Display the current portfolio (stock ticker, number of shares, initial price).
3. Update the portfolio display for purchases and sales.
4. Allow the user to sell all of the shares of a given stock.
5. Give the user an initial cash balance, and update and display the balance according to the
user's purchases and sales.
6. Ignore any transaction that causes the cash position to go below $0.
USE OF PREVIOUS StockHolding and PortfolioList LABS IS ADVISED. (I've including my
solutions to these below)
This is my written code from earlier homework:
public class StockHolding {
private String ticker;
private int numShares;
private double initialSharePrice;
private double currentSharePrice;
public StockHolding(String ticker, int numberShares, double initialPrice) {
this.ticker = ticker;
numShares = numberShares;
initialSharePrice = initialPrice;
currentSharePrice = initialPrice;
}
public double getCurrentValue() {
return numShares * getCurrentSharePrice();
}
public double getInitialCost() {
return numShares * getInitialSharePrice();
}
public double getCurrentProfit() {
return getCurrentValue() - getInitialCost();
}
public double getCurrentSharePrice() {
return currentSharePrice;
}
public void setCurrentSharePrice(double currentSharePrice) {
this.currentSharePrice = currentSharePrice;
}
public String getTicker() {
return ticker;
}
public int getShares() {
return numShares;
}
public double getInitialSharePrice() {
return initialSharePrice;
}
@Override
public String toString() {
return "Stock " + ticker + ", " + numShares + ", shares bought at "
+ initialSharePrice + ", current price "
+ currentSharePrice;
}
}
AND
import java.util.ArrayList;
public class PortfolioList {
private ArrayList portfolio;
public PortfolioList() {
portfolio = new ArrayList();
}
public void add(StockHolding stock) {
portfolio.add(stock);
}
public StockHolding find(String ticker) {
for (int i = 0; i < portfolio.size(); i++) {
StockHolding sh = portfolio.get(i);
if (sh.getTicker().equals(ticker)) {
return sh;
}
}
return null;
}
public void remove(String ticker) {
int pos = -1;
for (int i = 0; i < portfolio.size(); i++) {
StockHolding sh = portfolio.get(i);
if (sh.getTicker().equals(ticker)) {
pos = i;
}
}
if (pos != -1) {
portfolio.remove(pos);
}
}
I've been staring at this for two days, and I am lost. Please, any guidance/help would be greatly
appreciated.
Honestly don't even need a full solution, just need something to kick start. A comment skeleton
would help a ton. Thanks!
Solution
SOURCE CODE:
package stock;
public class StockHolding {
private String ticker;
private int numShares;
private double initialSharePrice;
private double currentSharePrice;
public StockHolding(String ticker, int numberShares, double initialPrice) {
this.ticker = ticker;
numShares = numberShares;
initialSharePrice = initialPrice;
currentSharePrice = initialPrice;
}
public double getCurrentValue() {
return numShares * getCurrentSharePrice();
}
public double getInitialCost() {
return numShares * getInitialSharePrice();
}
public double getCurrentProfit() {
return getCurrentValue() - getInitialCost();
}
public double getCurrentSharePrice() {
return currentSharePrice;
}
public void setCurrentSharePrice(double currentSharePrice) {
this.currentSharePrice = currentSharePrice;
}
public String getTicker() {
return ticker;
}
public int getShares() {
return numShares;
}
public double getInitialSharePrice() {
return initialSharePrice;
}
public void setNumShares(int numShares) {
this.numShares = numShares;
}
@Override
public String toString() {
return "Stock " + ticker + ", " + numShares + ", shares bought at "
+ initialSharePrice + ", current price "
+ currentSharePrice;
}
}
--------------------------------------------------------------------------------------------------------------------
---
package stock;
import java.util.ArrayList;
/**
*
* @author Gojkid
*/
public class PortfolioList {
private ArrayList portfolio;
public PortfolioList() {
portfolio = new ArrayList();
}
public void add(StockHolding stock) {
portfolio.add(stock);
}
public StockHolding find(String ticker) {
for (int i = 0; i < portfolio.size(); i++) {
StockHolding sh = portfolio.get(i);
if (sh.getTicker().equals(ticker)) {
return sh;
}
}
return null;
}
public int getPos(StockHolding sh)
{
return portfolio.indexOf(sh);
}
public int getSize()
{
return portfolio.size();
}
public StockHolding getElement(int i) {
return portfolio.get(i);
}
public void remove(String ticker) {
int pos = -1;
for (int i = 0; i < portfolio.size(); i++) {
StockHolding sh = portfolio.get(i);
if (sh.getTicker().equals(ticker)) {
pos = i;
}
}
if (pos != -1) {
portfolio.remove(pos);
}
}
}
--------------------------------------------------------------------------------------------------------------------
---
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* StockTrading.java
*
* Created on Nov 29, 2016, 12:43:57 AM
*/
package stock;
import javax.swing.table.DefaultTableModel;
public class StockTrading extends javax.swing.JFrame {
/** Creates new form StockTrading */
public StockTrading() {
initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
ticker = new javax.swing.JComboBox();
jScrollPane1 = new javax.swing.JScrollPane();
portfolio = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
price = new javax.swing.JTextField();
number = new javax.swing.JSpinner();
buy = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
balance = new javax.swing.JTextField();
sell = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
message = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Stock Trading Program");
ticker.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "A – Agilent
Technologies", "AAPL – Apple Inc.", "BRK.A – Berkshire Hathaway", "C – Citigroup",
"GOOG – Alphabet Inc.", "HOG – Harley-Davidson Inc.", "HPQ – Hewlett-Packard",
"INTC – Intel", "KO – The Coca-Cola Company", "LUV - Southwest Airlines", "MMM –
Minnesota Mining and Manufacturing", "MSFT – Microsoft", "T - AT&T", "TGT – Target
Corporation", "TXN – Texas Instruments", "WMT – Walmart" }));
portfolio.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Ticker", "Number", "Current Price", "Intial Price"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(portfolio);
jLabel1.setText("Ticker :");
jLabel2.setText("Price:");
number.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1),
Integer.valueOf(1), null, Integer.valueOf(1)));
buy.setText("Buy");
buy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buyActionPerformed(evt);
}
});
jLabel3.setText("Remaining Balance:");
balance.setText("$10000");
sell.setText("Sell");
sell.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sellActionPerformed(evt);
}
});
jLabel4.setText("User's Portfolio");
message.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
message.setText(" ");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 723,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(103, 103, 103)
.addComponent(jLabel3)
.addGap(29, 29, 29)
.addComponent(balance, javax.swing.GroupLayout.PREFERRED_SIZE, 67,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34,
Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 291,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buy)
.addGap(31, 31, 31)
.addComponent(sell))
.addGroup(layout.createSequentialGroup()
.addComponent(ticker, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, 57,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(message, javax.swing.GroupLayout.PREFERRED_SIZE, 489,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(39, 39, 39))
.addGroup(layout.createSequentialGroup()
.addGap(365, 365, 365)
.addComponent(jLabel4)
.addContainerGap(878, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 228,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(67, 67, 67)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(balance, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(102, 102, 102)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ticker, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buy)
.addComponent(sell))
.addGap(64, 64, 64)
.addComponent(message)))
.addContainerGap(69, Short.MAX_VALUE))
);
pack();
}
private void buyActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
message.setText("");
price.setText(""+(int)(Math.random()*1000+Math.random()*100+Math.random()*10));
double p = Double.parseDouble(price.getText());
int n = ((Integer)number.getValue()).intValue();
StockHolding sh=new StockHolding((String)ticker.getSelectedItem(),n,p);
if(Double.parseDouble(balance.getText().substring(1))>=(p*n))
{
userPortfolio.add(sh);
bal=Double.parseDouble(balance.getText().substring(1))-(n*p);
balance.setText("$"+(int)bal);
}
else
message.setText("You don't have enough money to buy these shares");
updateTable();
}
private void sellActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
message.setText("");
if(userPortfolio.find((String)ticker.getSelectedItem())!=null)
{
if(userPortfolio.find((String)ticker.getSelectedItem()).getShares()>=((Integer)number.getValue()
).intValue())
{
bal =
Double.parseDouble(balance.getText().substring(1))+userPortfolio.find((String)ticker.getSelecte
dItem()).getCurrentSharePrice()*((Integer)number.getValue()).intValue();
userPortfolio.find((String)ticker.getSelectedItem()).setNumShares(userPortfolio.find((String)tick
er.getSelectedItem()).getShares()-((Integer)number.getValue()).intValue());
balance.setText("$"+(int)bal);
}
else
if(Double.parseDouble(balance.getText().substring(1))==(userPortfolio.find((String)ticker.getSel
ectedItem()).getCurrentSharePrice()*((Integer)number.getValue()).intValue()))
{
bal=Double.parseDouble(balance.getText().substring(1))-
(((Integer)number.getValue()).intValue()*userPortfolio.find((String)ticker.getSelectedItem()).get
CurrentSharePrice());
DefaultTableModel dtm = (DefaultTableModel) portfolio.getModel();
dtm.removeRow(userPortfolio.getPos(userPortfolio.find((String)ticker.getSelectedItem())));
userPortfolio.remove((String)ticker.getSelectedItem());
balance.setText("$"+(int)bal);
}
else
message.setText("You only have
"+userPortfolio.find((String)ticker.getSelectedItem()).getShares()+" shares
of"+ticker.getSelectedItem());
}
else
message.setText("You don't have any "+ticker.getSelectedItem()+" shares");
updateTable();
}
public void updateTable()
{
for (int i = 0; i < userPortfolio.getSize(); i++) {
StockHolding sh = userPortfolio.getElement(i);
if(i <= userPortfolio.getSize())
{
DefaultTableModel dtm = (DefaultTableModel) portfolio.getModel();
dtm.addRow(new Object[]{"", "", "",""});
}
sh.setCurrentSharePrice(sh.getInitialSharePrice()+Math.random()*10);
portfolio.setValueAt(sh.getTicker(), i, 0 );
portfolio.setValueAt(sh.getShares()+"", i, 1 );
portfolio.setValueAt("$"+(int)sh.getCurrentSharePrice(), i, 2 );
portfolio.setValueAt("$"+(int)sh.getInitialSharePrice(), i, 3 );
}
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S
EVERE, null, ex);
}
//
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new StockTrading().setVisible(true);
}
});
}
private javax.swing.JTextField balance;
private javax.swing.JButton buy;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel message;
private javax.swing.JSpinner number;
private javax.swing.JTable portfolio;
private javax.swing.JTextField price;
private javax.swing.JButton sell;
private javax.swing.JComboBox ticker;
private PortfolioList userPortfolio = new PortfolioList();
private double bal;
}

More Related Content

Similar to You are to write a GUI program that will allow a user to buy, sell a.pdf

Smart Pointer in C++
Smart Pointer in C++Smart Pointer in C++
Smart Pointer in C++
永泉 韩
 
Minimum viable product_to_deliver_business_value_v0.4
Minimum viable product_to_deliver_business_value_v0.4Minimum viable product_to_deliver_business_value_v0.4
Minimum viable product_to_deliver_business_value_v0.4
Archana Joshi
 
Write a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdfWrite a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdf
eyebolloptics
 
ITECH 2100 Programming 2 School of Science, Information Te.docx
ITECH 2100 Programming 2 School of Science, Information Te.docxITECH 2100 Programming 2 School of Science, Information Te.docx
ITECH 2100 Programming 2 School of Science, Information Te.docx
christiandean12115
 
show code and all classes with full implementation for these Program S.pdf
show code and all classes with full implementation for these Program S.pdfshow code and all classes with full implementation for these Program S.pdf
show code and all classes with full implementation for these Program S.pdf
AlanSmDDyerl
 

Similar to You are to write a GUI program that will allow a user to buy, sell a.pdf (20)

Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Smart Pointer in C++
Smart Pointer in C++Smart Pointer in C++
Smart Pointer in C++
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
 
Softwaredesignpatterns ppt-130430202602-phpapp02
Softwaredesignpatterns ppt-130430202602-phpapp02Softwaredesignpatterns ppt-130430202602-phpapp02
Softwaredesignpatterns ppt-130430202602-phpapp02
 
Minimum viable product_to_deliver_business_value_v0.4
Minimum viable product_to_deliver_business_value_v0.4Minimum viable product_to_deliver_business_value_v0.4
Minimum viable product_to_deliver_business_value_v0.4
 
Write a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdfWrite a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdf
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Lesson12 other behavioural patterns
Lesson12 other behavioural patternsLesson12 other behavioural patterns
Lesson12 other behavioural patterns
 
ITECH 2100 Programming 2 School of Science, Information Te.docx
ITECH 2100 Programming 2 School of Science, Information Te.docxITECH 2100 Programming 2 School of Science, Information Te.docx
ITECH 2100 Programming 2 School of Science, Information Te.docx
 
show code and all classes with full implementation for these Program S.pdf
show code and all classes with full implementation for these Program S.pdfshow code and all classes with full implementation for these Program S.pdf
show code and all classes with full implementation for these Program S.pdf
 
Estructura secuencial -garcia
Estructura secuencial -garciaEstructura secuencial -garcia
Estructura secuencial -garcia
 
Morgagebuildclasses.netbeans_automatic_buildMorgagebui.docx
Morgagebuildclasses.netbeans_automatic_buildMorgagebui.docxMorgagebuildclasses.netbeans_automatic_buildMorgagebui.docx
Morgagebuildclasses.netbeans_automatic_buildMorgagebui.docx
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase framework
 
Clean code
Clean codeClean code
Clean code
 

More from jyothimuppasani1

Help please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdfHelp please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdf
jyothimuppasani1
 
how can I replace the Newsfeed text with a custom on in SharePoi.pdf
how can I replace the Newsfeed text with a custom on in SharePoi.pdfhow can I replace the Newsfeed text with a custom on in SharePoi.pdf
how can I replace the Newsfeed text with a custom on in SharePoi.pdf
jyothimuppasani1
 
Hello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdfHello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdf
jyothimuppasani1
 
File encryption. [32] Write a program which accepts a filename as a .pdf
File encryption. [32] Write a program which accepts a filename as a .pdfFile encryption. [32] Write a program which accepts a filename as a .pdf
File encryption. [32] Write a program which accepts a filename as a .pdf
jyothimuppasani1
 
Explain the relevance that medical standards of practice have to one.pdf
Explain the relevance that medical standards of practice have to one.pdfExplain the relevance that medical standards of practice have to one.pdf
Explain the relevance that medical standards of practice have to one.pdf
jyothimuppasani1
 
Find the mission and values statements for four different hospita.pdf
Find the mission and values statements for four different hospita.pdfFind the mission and values statements for four different hospita.pdf
Find the mission and values statements for four different hospita.pdf
jyothimuppasani1
 
Do you think that nonhuman animals have interests Does this mean th.pdf
Do you think that nonhuman animals have interests Does this mean th.pdfDo you think that nonhuman animals have interests Does this mean th.pdf
Do you think that nonhuman animals have interests Does this mean th.pdf
jyothimuppasani1
 
Discuss the importance of recognizing and implementing different ent.pdf
Discuss the importance of recognizing and implementing different ent.pdfDiscuss the importance of recognizing and implementing different ent.pdf
Discuss the importance of recognizing and implementing different ent.pdf
jyothimuppasani1
 
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdfData Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
jyothimuppasani1
 
•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf
jyothimuppasani1
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdf
jyothimuppasani1
 
What are the factors that contribute to H+ gain or loss How do lung.pdf
What are the factors that contribute to H+ gain or loss How do lung.pdfWhat are the factors that contribute to H+ gain or loss How do lung.pdf
What are the factors that contribute to H+ gain or loss How do lung.pdf
jyothimuppasani1
 
Write down the four (4) nonlinear regression models covered in class,.pdf
Write down the four (4) nonlinear regression models covered in class,.pdfWrite down the four (4) nonlinear regression models covered in class,.pdf
Write down the four (4) nonlinear regression models covered in class,.pdf
jyothimuppasani1
 

More from jyothimuppasani1 (20)

How does an open source operating system like Linux® affect Internet.pdf
How does an open source operating system like Linux® affect Internet.pdfHow does an open source operating system like Linux® affect Internet.pdf
How does an open source operating system like Linux® affect Internet.pdf
 
Help please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdfHelp please!!(Include your modified DList.java source code file in.pdf
Help please!!(Include your modified DList.java source code file in.pdf
 
how can I replace the Newsfeed text with a custom on in SharePoi.pdf
how can I replace the Newsfeed text with a custom on in SharePoi.pdfhow can I replace the Newsfeed text with a custom on in SharePoi.pdf
how can I replace the Newsfeed text with a custom on in SharePoi.pdf
 
Hello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdfHello!This is Java assignment applet.Can someone help me writing.pdf
Hello!This is Java assignment applet.Can someone help me writing.pdf
 
For each of the following reseach questions identify the observation.pdf
For each of the following reseach questions identify the observation.pdfFor each of the following reseach questions identify the observation.pdf
For each of the following reseach questions identify the observation.pdf
 
Find an Eulerian trail in the following graph. Be sure to indicate th.pdf
Find an Eulerian trail in the following graph. Be sure to indicate th.pdfFind an Eulerian trail in the following graph. Be sure to indicate th.pdf
Find an Eulerian trail in the following graph. Be sure to indicate th.pdf
 
File encryption. [32] Write a program which accepts a filename as a .pdf
File encryption. [32] Write a program which accepts a filename as a .pdfFile encryption. [32] Write a program which accepts a filename as a .pdf
File encryption. [32] Write a program which accepts a filename as a .pdf
 
Explain the relevance that medical standards of practice have to one.pdf
Explain the relevance that medical standards of practice have to one.pdfExplain the relevance that medical standards of practice have to one.pdf
Explain the relevance that medical standards of practice have to one.pdf
 
Find the mission and values statements for four different hospita.pdf
Find the mission and values statements for four different hospita.pdfFind the mission and values statements for four different hospita.pdf
Find the mission and values statements for four different hospita.pdf
 
Did colonial rule freeze colonized societies by preserving old s.pdf
Did colonial rule freeze colonized societies by preserving old s.pdfDid colonial rule freeze colonized societies by preserving old s.pdf
Did colonial rule freeze colonized societies by preserving old s.pdf
 
Do you think that nonhuman animals have interests Does this mean th.pdf
Do you think that nonhuman animals have interests Does this mean th.pdfDo you think that nonhuman animals have interests Does this mean th.pdf
Do you think that nonhuman animals have interests Does this mean th.pdf
 
Discuss the importance of recognizing and implementing different ent.pdf
Discuss the importance of recognizing and implementing different ent.pdfDiscuss the importance of recognizing and implementing different ent.pdf
Discuss the importance of recognizing and implementing different ent.pdf
 
Considering the challenges she is facing, what Anitas plan before .pdf
Considering the challenges she is facing, what Anitas plan before .pdfConsidering the challenges she is facing, what Anitas plan before .pdf
Considering the challenges she is facing, what Anitas plan before .pdf
 
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdfData Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdf
 
Conceptual skills are most important at theSolutionConceptual .pdf
Conceptual skills are most important at theSolutionConceptual .pdfConceptual skills are most important at theSolutionConceptual .pdf
Conceptual skills are most important at theSolutionConceptual .pdf
 
A variable whose scope is restricted to the method where it was decl.pdf
A variable whose scope is restricted to the method where it was decl.pdfA variable whose scope is restricted to the method where it was decl.pdf
A variable whose scope is restricted to the method where it was decl.pdf
 
•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdf
 
What are the factors that contribute to H+ gain or loss How do lung.pdf
What are the factors that contribute to H+ gain or loss How do lung.pdfWhat are the factors that contribute to H+ gain or loss How do lung.pdf
What are the factors that contribute to H+ gain or loss How do lung.pdf
 
Write down the four (4) nonlinear regression models covered in class,.pdf
Write down the four (4) nonlinear regression models covered in class,.pdfWrite down the four (4) nonlinear regression models covered in class,.pdf
Write down the four (4) nonlinear regression models covered in class,.pdf
 

Recently uploaded

MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MysoreMuleSoftMeetup
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdfContoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdf
cupulin
 

Recently uploaded (20)

COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdfContoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdf
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 

You are to write a GUI program that will allow a user to buy, sell a.pdf

  • 1. You are to write a GUI program that will allow a user to buy, sell and view stocks in a stock portfolio. Objective: 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. Program Capabilities: 1. Allow a user to buy a stock with a given number of shares and price per share. 2. Display the current portfolio (stock ticker, number of shares, initial price). 3. Update the portfolio display for purchases and sales. 4. Allow the user to sell all of the shares of a given stock. 5. Give the user an initial cash balance, and update and display the balance according to the user's purchases and sales. 6. Ignore any transaction that causes the cash position to go below $0. USE OF PREVIOUS StockHolding and PortfolioList LABS IS ADVISED. (I've including my solutions to these below) This is my written code from earlier homework: public class StockHolding { private String ticker; private int numShares; private double initialSharePrice; private double currentSharePrice; public StockHolding(String ticker, int numberShares, double initialPrice) { this.ticker = ticker; numShares = numberShares; initialSharePrice = initialPrice; currentSharePrice = initialPrice; } public double getCurrentValue() { return numShares * getCurrentSharePrice(); } public double getInitialCost() {
  • 2. return numShares * getInitialSharePrice(); } public double getCurrentProfit() { return getCurrentValue() - getInitialCost(); } public double getCurrentSharePrice() { return currentSharePrice; } public void setCurrentSharePrice(double currentSharePrice) { this.currentSharePrice = currentSharePrice; } public String getTicker() { return ticker; } public int getShares() { return numShares; } public double getInitialSharePrice() { return initialSharePrice; } @Override public String toString() { return "Stock " + ticker + ", " + numShares + ", shares bought at " + initialSharePrice + ", current price " + currentSharePrice; } } AND import java.util.ArrayList; public class PortfolioList { private ArrayList portfolio; public PortfolioList() { portfolio = new ArrayList();
  • 3. } public void add(StockHolding stock) { portfolio.add(stock); } public StockHolding find(String ticker) { for (int i = 0; i < portfolio.size(); i++) { StockHolding sh = portfolio.get(i); if (sh.getTicker().equals(ticker)) { return sh; } } return null; } public void remove(String ticker) { int pos = -1; for (int i = 0; i < portfolio.size(); i++) { StockHolding sh = portfolio.get(i); if (sh.getTicker().equals(ticker)) { pos = i; } } if (pos != -1) { portfolio.remove(pos); } } I've been staring at this for two days, and I am lost. Please, any guidance/help would be greatly appreciated. Honestly don't even need a full solution, just need something to kick start. A comment skeleton would help a ton. Thanks! Solution SOURCE CODE:
  • 4. package stock; public class StockHolding { private String ticker; private int numShares; private double initialSharePrice; private double currentSharePrice; public StockHolding(String ticker, int numberShares, double initialPrice) { this.ticker = ticker; numShares = numberShares; initialSharePrice = initialPrice; currentSharePrice = initialPrice; } public double getCurrentValue() { return numShares * getCurrentSharePrice(); } public double getInitialCost() { return numShares * getInitialSharePrice(); } public double getCurrentProfit() { return getCurrentValue() - getInitialCost(); } public double getCurrentSharePrice() { return currentSharePrice; } public void setCurrentSharePrice(double currentSharePrice) { this.currentSharePrice = currentSharePrice; } public String getTicker() { return ticker; }
  • 5. public int getShares() { return numShares; } public double getInitialSharePrice() { return initialSharePrice; } public void setNumShares(int numShares) { this.numShares = numShares; } @Override public String toString() { return "Stock " + ticker + ", " + numShares + ", shares bought at " + initialSharePrice + ", current price " + currentSharePrice; } } -------------------------------------------------------------------------------------------------------------------- --- package stock; import java.util.ArrayList; /** * * @author Gojkid */ public class PortfolioList { private ArrayList portfolio; public PortfolioList() { portfolio = new ArrayList(); } public void add(StockHolding stock) { portfolio.add(stock); }
  • 6. public StockHolding find(String ticker) { for (int i = 0; i < portfolio.size(); i++) { StockHolding sh = portfolio.get(i); if (sh.getTicker().equals(ticker)) { return sh; } } return null; } public int getPos(StockHolding sh) { return portfolio.indexOf(sh); } public int getSize() { return portfolio.size(); } public StockHolding getElement(int i) { return portfolio.get(i); } public void remove(String ticker) { int pos = -1; for (int i = 0; i < portfolio.size(); i++) { StockHolding sh = portfolio.get(i); if (sh.getTicker().equals(ticker)) { pos = i; } } if (pos != -1) { portfolio.remove(pos); } } } -------------------------------------------------------------------------------------------------------------------- ---
  • 7. /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * StockTrading.java * * Created on Nov 29, 2016, 12:43:57 AM */ package stock; import javax.swing.table.DefaultTableModel; public class StockTrading extends javax.swing.JFrame { /** Creates new form StockTrading */ public StockTrading() { initComponents(); } @SuppressWarnings("unchecked") private void initComponents() { ticker = new javax.swing.JComboBox(); jScrollPane1 = new javax.swing.JScrollPane(); portfolio = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); price = new javax.swing.JTextField(); number = new javax.swing.JSpinner(); buy = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); balance = new javax.swing.JTextField(); sell = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); message = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Stock Trading Program"); ticker.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "A – Agilent Technologies", "AAPL – Apple Inc.", "BRK.A – Berkshire Hathaway", "C – Citigroup", "GOOG – Alphabet Inc.", "HOG – Harley-Davidson Inc.", "HPQ – Hewlett-Packard",
  • 8. "INTC – Intel", "KO – The Coca-Cola Company", "LUV - Southwest Airlines", "MMM – Minnesota Mining and Manufacturing", "MSFT – Microsoft", "T - AT&T", "TGT – Target Corporation", "TXN – Texas Instruments", "WMT – Walmart" })); portfolio.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Ticker", "Number", "Current Price", "Intial Price" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(portfolio); jLabel1.setText("Ticker :"); jLabel2.setText("Price:"); number.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1))); buy.setText("Buy"); buy.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buyActionPerformed(evt);
  • 9. } }); jLabel3.setText("Remaining Balance:"); balance.setText("$10000"); sell.setText("Sell"); sell.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sellActionPerformed(evt); } }); jLabel4.setText("User's Portfolio"); message.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); message.setText(" "); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 723, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(103, 103, 103) .addComponent(jLabel3) .addGap(29, 29, 29) .addComponent(balance, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
  • 10. .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 291, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(buy) .addGap(31, 31, 31) .addComponent(sell)) .addGroup(layout.createSequentialGroup() .addComponent(ticker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(33, 33, 33) .addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(message, javax.swing.GroupLayout.PREFERRED_SIZE, 489, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(39, 39, 39)) .addGroup(layout.createSequentialGroup() .addGap(365, 365, 365) .addComponent(jLabel4) .addContainerGap(878, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(33, 33, 33) .addComponent(jLabel4) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(67, 67, 67)
  • 11. .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(balance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(102, 102, 102) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ticker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(number, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(38, 38, 38) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(buy) .addComponent(sell)) .addGap(64, 64, 64) .addComponent(message))) .addContainerGap(69, Short.MAX_VALUE)) ); pack(); } private void buyActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: message.setText(""); price.setText(""+(int)(Math.random()*1000+Math.random()*100+Math.random()*10)); double p = Double.parseDouble(price.getText()); int n = ((Integer)number.getValue()).intValue(); StockHolding sh=new StockHolding((String)ticker.getSelectedItem(),n,p); if(Double.parseDouble(balance.getText().substring(1))>=(p*n)) { userPortfolio.add(sh); bal=Double.parseDouble(balance.getText().substring(1))-(n*p);
  • 12. balance.setText("$"+(int)bal); } else message.setText("You don't have enough money to buy these shares"); updateTable(); } private void sellActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: message.setText(""); if(userPortfolio.find((String)ticker.getSelectedItem())!=null) { if(userPortfolio.find((String)ticker.getSelectedItem()).getShares()>=((Integer)number.getValue() ).intValue()) { bal = Double.parseDouble(balance.getText().substring(1))+userPortfolio.find((String)ticker.getSelecte dItem()).getCurrentSharePrice()*((Integer)number.getValue()).intValue(); userPortfolio.find((String)ticker.getSelectedItem()).setNumShares(userPortfolio.find((String)tick er.getSelectedItem()).getShares()-((Integer)number.getValue()).intValue()); balance.setText("$"+(int)bal); } else if(Double.parseDouble(balance.getText().substring(1))==(userPortfolio.find((String)ticker.getSel ectedItem()).getCurrentSharePrice()*((Integer)number.getValue()).intValue())) { bal=Double.parseDouble(balance.getText().substring(1))- (((Integer)number.getValue()).intValue()*userPortfolio.find((String)ticker.getSelectedItem()).get CurrentSharePrice()); DefaultTableModel dtm = (DefaultTableModel) portfolio.getModel(); dtm.removeRow(userPortfolio.getPos(userPortfolio.find((String)ticker.getSelectedItem()))); userPortfolio.remove((String)ticker.getSelectedItem()); balance.setText("$"+(int)bal); } else message.setText("You only have
  • 13. "+userPortfolio.find((String)ticker.getSelectedItem()).getShares()+" shares of"+ticker.getSelectedItem()); } else message.setText("You don't have any "+ticker.getSelectedItem()+" shares"); updateTable(); } public void updateTable() { for (int i = 0; i < userPortfolio.getSize(); i++) { StockHolding sh = userPortfolio.getElement(i); if(i <= userPortfolio.getSize()) { DefaultTableModel dtm = (DefaultTableModel) portfolio.getModel(); dtm.addRow(new Object[]{"", "", "",""}); } sh.setCurrentSharePrice(sh.getInitialSharePrice()+Math.random()*10); portfolio.setValueAt(sh.getTicker(), i, 0 ); portfolio.setValueAt(sh.getShares()+"", i, 1 ); portfolio.setValueAt("$"+(int)sh.getCurrentSharePrice(), i, 2 ); portfolio.setValueAt("$"+(int)sh.getInitialSharePrice(), i, 3 ); } } public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } }
  • 14. } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S EVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S EVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S EVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(StockTrading.class.getName()).log(java.util.logging.Level.S EVERE, null, ex); } // /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new StockTrading().setVisible(true); } }); } private javax.swing.JTextField balance; private javax.swing.JButton buy; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel message; private javax.swing.JSpinner number; private javax.swing.JTable portfolio; private javax.swing.JTextField price; private javax.swing.JButton sell; private javax.swing.JComboBox ticker; private PortfolioList userPortfolio = new PortfolioList();