📄 stocktable.java
字号:
package com.pepsan.framework;/* * A table of stocks and quotes. The stocks in the table are fixed. * The quotes are retreived dynamically over the Internet from Yahoo's site. * * The length of the table is not fixed. * * Copyright (c) 1999 Pepsan & Associates, Inc. */import javax.swing.*;import javax.swing.table.*;import javax.swing.border.*;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.awt.BorderLayout;import java.awt.Dimension;import java.awt.Color;import java.net.*;import java.awt.event.*;import java.io.*;public class StockTable extends JFrame { final TableModel dataModel; // These two strings are Yahoo magic. They could change, by Yahoo, at any // time and break this little bit of code. final String quotePrefix = "http://quote.yahoo.com/d/quotes.csv?s="; final String quoteSuffix = "&f=sl1d1t1c1ohgv&e=.csv"; final JFrame frame = this; public StockTable() { super("Stock Quotes"); // Headings for table final String[] names = {"Company", "Symbol", "Current Price", "Own?"}; // List of stocks final Object[][] data = { {"Apple", "AAPL", new Float(0.0), new Boolean(true)}, {"Cisco", "CSCO", new Float(0.0), new Boolean(false)}, {"CNET", "CNET", new Float(0.0), new Boolean(true)}, {"MCI Worldcom", "WCOM", new Float(0.0), new Boolean(true)}, {"Adaptec", "ADPT", new Float(0.0), new Boolean(false)}, }; // Handle window closing frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { frame.setVisible(false); } }); // A simple table model dataModel = new AbstractTableModel() { // These methods always need to be implemented. public int getColumnCount() { return names.length; } public int getRowCount() { return data.length;} public Object getValueAt(int row, int col) {return data[row][col];} public String getColumnName(int column) {return names[column];} public Class getColumnClass(int col) { return getValueAt(0,col).getClass(); } public boolean isCellEditable(int row, int col) {return false;} public void setValueAt(Object aValue, int row, int column) { data[row][column] = aValue; fireTableCellUpdated(row, column); } }; // Whoppee. The table sorts! TableSorter sorter = new TableSorter(dataModel); JTable tableView = new JTable(sorter); sorter.addMouseListenerToHeaderInTable(tableView); // Of course we want a scrolling table JScrollPane scrollpane = new JScrollPane(tableView); scrollpane.setPreferredSize(new Dimension(400, 150)); // Clicking this button causes a background update in a Swing worker object JButton updateButton = new JButton("Update Prices"); updateButton.setBackground(Color.green); // The update button kicks of a Swing worker object to run the update // This allows the rest of the application to keep running while we fetch the data // It is here to remind people that Swing is not thread safe... // See <http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html> for more info. // // We show a progress bar to prove we're doing something updateButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final SwingWorker worker = new SwingWorker() { public Object construct() { JProgressBar pBar = new JProgressBar(0, data.length); pBar.setStringPainted(true); JLabel quoteLabel = new JLabel((String) dataModel.getValueAt(0,0), SwingConstants.CENTER); // This dialog is not modal JDialog pDialog = new JDialog(frame, "Getting Initial Quotes", false); pDialog.getContentPane().add(pBar, BorderLayout.CENTER); pDialog.getContentPane().add(quoteLabel, BorderLayout.SOUTH); pDialog.pack(); pDialog.show(); // For each stock in the table, fetch a quote // The quote should be the second field, comma separated. Of course Yahoo could change // this at any time for (int i=0; i<data.length; i++) { dataModel.setValueAt(getQuote(quotePrefix + dataModel.getValueAt(i,1) + quoteSuffix), i, 2); quoteLabel.setText((String) dataModel.getValueAt(i,0)); pBar.setValue(i+1); } pDialog.dispose(); return ""; // We have to return an Object, doesn't matter what } public void finished() { // Actually nothing to do here, but we could do something!!! :-) } }; } }); frame.getContentPane().add(scrollpane, BorderLayout.CENTER); frame.getContentPane().add(updateButton, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); // Get stock quotes now (this is blocking, unlike the update button) // This is a funky way to show a bunch of text in a dialog Object[] diabolical = new Object[] { "This fetches quotes in the main thread and so blocks all other activity.", "Hit OK to continue.", "Cancel not allowed :-)", "Yes it's diabolical! Muhahahaha!!!", "But it illustrates threading...", "The Update button updates in a SwingWorker thread.", "It's available to update quotes once this finishes.", "Try it and see!", "For now, just hit OK and wait for the completion dialog to appear"}; JOptionPane startPane = new JOptionPane(diabolical, JOptionPane.INFORMATION_MESSAGE); JDialog startDialog = startPane.createDialog(frame, "Gettings Quotes"); // This will block until the user hits OK startDialog.show(); // For each stock in the table, fetch a quote // The quote should be the second field, comma separated. Of course Yahoo could change // this at any time for (int i=0; i<data.length; i++) { dataModel.setValueAt(getQuote(quotePrefix + dataModel.getValueAt(i,1) + quoteSuffix), i, 2); } JOptionPane donePane = new JOptionPane("Initial quotes received! Hit Update to stay current.", JOptionPane.INFORMATION_MESSAGE); JDialog doneDialog = donePane.createDialog(frame, "Got Quotes"); doneDialog.show(); } // Use the URL class to grab the quote from Yahoo // The quote should be comma separated with the price the second field // This is a *really* ugly way to parse the return string :( Don't do it this way! private Float getQuote(String quoteString) { int curByte; char curChar; String curQuote; boolean priceFlag; try { URL quoteURL = new URL(quoteString); try { DataInputStream quoteStream = new DataInputStream(quoteURL.openStream()); priceFlag = false; curQuote = ""; while( (curByte = quoteStream.read()) != -1) { curChar = (char) curByte; if (!priceFlag && (curChar == ',')) { priceFlag = true; continue; } if (priceFlag) { if (curChar == ',') { break; } else { curQuote += curChar; } } } return new Float(curQuote); } catch (IOException e) { System.err.println("getContent on quote failed: " + e); } } catch (MalformedURLException e) { System.err.println("Yikes. URL exception"); } // Return a -1.0 if the fetch failed return new Float(-1.0); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -