我目前正在进行我的第三年编程项目及其作品集跟踪器。:/ 我已经创建了 Stock_API 和 Portfolio_API 接口(以及它们的实现)和一个 GUI 类,它在实例化时采用两个参数:
public GUI(Portfolio_API p, Stock s){
tempPort = p;
tempStock = s;
}
我使用此构造函数作为将这些接口的实现引入 GUI 而不将实现暴露给 GUI 的一种方式(这是该项目的主要目标之一)。投资组合对象有一个名称(字符串)和一个 ArrayList。股票对象具有股票代码(字符串)、股票名称(字符串)、股票价值(浮动)、股票数量(整数)和持有价值(浮动)。
在 GUI 中,我有一个 portCollection 数组列表,其中包含类型为 portfolio_API 的对象,这样系统就可以跟踪多个投资组合。正如上面代码块中提到的,还有一个 tempStock 和 tempPort 对象。
很抱歉给你这么多关于这个程序的细节,但我认为最好这样我才能了解上下文。无论如何,手头的问题。我有一种方法,它使用 GUI 获取股票代码、股票名称和股票数量,并将股票添加到当前打开的投资组合中(每个投资组合都有自己的选项卡)。该方法如下所示:
public void addStock() {
int num_shares = 0;
float dailyChange = 0.0f;
float stockValue = 0.0f;
boolean succeed = true;
// GUI gets information of stock from user
String ticker = JOptionPane.showInputDialog(frame,
"Enter the ticker symbol:");
String stockName = JOptionPane.showInputDialog(frame,
"Enter the Stock name:");
try {
num_shares = Integer.parseInt(JOptionPane.showInputDialog(frame,
"Enter the number of shares:"));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(frame,
"Number of shares was not an integer. Try again");
succeed = false;
}
// If parsing was successful...
if (succeed) {
tempStock.setTicker(ticker);
tempStock.setNumberOfShares(num_shares);
tempStock.setStockName(stockName);
// Fetches newest value using the current ticker symbol
boolean succeedUpdate = tempStock.updateShareValue();
if (succeedUpdate) {
tempStock.calculateValueOfHolding();
// Adds to the current portfolio...
String tabName = tabbedPane.getTitleAt(tabbedPane
.getSelectedIndex());
System.out.println(tabName);
findPortfolio(tabName).addStock(tempStock);
findPortfolio(tabName).sort();
// ...Then adds it to the table
JPanel j = (JPanel) tabbedPane.getSelectedComponent()
.getComponentAt(0, 0);
JViewport v = ((JScrollPane) j.getComponent(0)).getViewport();
JTable table = (JTable) v.getComponent(0);
float currentTotal = findPortfolio(tabName).getTotal();
// Updates the total label
((JLabel) j.getComponent(1)).setText("Total: " + currentTotal);
Object[] newStock = { tempStock.getTicker(),
tempStock.getStockName(),
tempStock.getNumberOfShares(),
tempStock.getShareValue(),
tempStock.getValueOfHolding() };
((DefaultTableModel) table.getModel()).addRow(newStock);
}
}
}
当我添加不止一只股票时,新股票会取代旧股票并有效地覆盖它。我认为这是对 tempStock 的重用。不知道为什么如果我将变量添加到数组列表中,它肯定会成为该数组列表的一部分并且不需要与 tempStock 变量关联?
与上述 arraylists 一起使用的方法:
private Portfolio_API findPortfolio(String name) {
Portfolio_API p = null;
for (int i = 0; i < portCollection.size(); i++) {
if (portCollection.get(i).getName() == name) {
p = portCollection.get(i);
}
}
这两个在 Portfolio 类中:
@Override
public boolean addStock(Stock_API s) {
if (!doesExist(s)) {
portfolio.add(s);
return true;
} else {
return false;
}
}
@Override
public boolean doesExist(Stock_API s) {
boolean found = false;
for (int i = 0; i < portfolio.size(); i++) {
if (portfolio.get(i).getTicker() == s.getTicker()) {
found = true;
}
}
return found;
}
我只是来这里寻求帮助,因为我碰壁了,我真的需要帮助。如果有人能给我任何建议,我将永远欠你的债。
谢谢,克里斯