Custom model, POJO and JTable : Table Model « Swing JFC « Java






Custom model, POJO and JTable

Custom model, POJO and JTable
     
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O'Reilly 
*/
// MarketTable.java
//An application that display stock market data in a JTable. The table
//uses the MarketDataModel class for its model. MYOSM should be running
//to make the data dynamic.
//

import java.awt.BorderLayout;
import java.util.Date;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

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);
  }
}

//MarketDataModel.java
//A custom table model for use with the MYOSM enviornment.
//

class MarketDataModel extends AbstractTableModel implements Runnable {

  Thread runner;

  MYOSM market;

  int delay;

  public MarketDataModel(int initialDelay) {
    market = new MYOSM();
    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) {
      }
    }
  }
}

//Stock.java
//A simple aggregate class for storing stock market information on a single
//stock (symbol, price, etc.).
//

class Stock {
  String symbol;

  double price;

  double delta;

  Date lastUpdate;

  public Stock(String s, double p) {
    symbol = s;
    price = p;
    lastUpdate = new Date();
  }

  public void update(double d) {
    delta = d;
    price += delta;
  }

  public void print() {
    System.out.println(symbol + ": " + price + " (" + delta
        + ") last updated " + lastUpdate);
  }
}

//MYOSM.java
//Make Your Own Stock Market: A simple stock market simulator that contains a
//few stocks and their current prices (and deltas). It randomly adjusts the
//prices on stocks to give a dynamic feel to the data.
//

class MYOSM 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 MYOSM() {
    // Not meant to be shown as a real frame
    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. It's not meant to be used with other programs,
  // but rather as a debugging tool to make sure the market runs ok.
  public MYOSM(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();
  }

  // Here's the heart of our stock market. 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[]) {
    MYOSM myMarket = new MYOSM(args.length > 0);
    myMarket.setVisible(true);
  }
}

           
         
    
    
    
    
  








Related examples in the same category

1.Append a row to a table through DefaultTableModel at specified row
2.Remove the first row from a table with DefaultTableModel
3.Remove the last row from a table with DefaultTableModel
4.Move the first row to the end of the table
5.Move the last row to the beginning of the table
6.Move the first two rows to the end of the table
7.Move the last two rows to the start of the table
8.Get all the table data from DefaultTableModel
9.Copy (clone) the data from the second row
10.Overwrite the date from the first row with DefaultTableModel
11.Copy data from a table to a list
12.Insert a new column to a table
13.JTable class using default table models and a convenienceJTable class using default table models and a convenience
14.extends DefaultTableModel to create your own table model and build table from thatextends DefaultTableModel to create your own table model and build table from that
15.Table with a custom TableModelTable with a custom TableModel
16.extends AbstractTableModel to create custom modelextends AbstractTableModel to create custom model
17.Table model is based on call backTable model is based on call back
18.Hard code data in array for TableModelHard code data in array for TableModel
19.A JTable class using default table models and a convenience constructorA JTable class using default table models and a convenience constructor
20.Custom table model, File data based ModelCustom table model, File data based Model
21.Paging or pagable JTable(Table) Model for large data setPaging or pagable JTable(Table) Model for large data set
22.Paging JTable(Table) Model with an input field for dynamically altering the size of a page.Paging JTable(Table) Model with an input field for dynamically altering the size of a page.
23.File data Table: file name, size, type File data Table: file name, size, type
24.Stocks data Table: illustrate the TableModel Stocks data Table: illustrate the TableModel
25.AbstractTableModel backed by HashtableAbstractTableModel backed by Hashtable
26.Fixed data vs dynamic data TableFixed data vs dynamic data Table
27.Use model to control the Editable ColumnsUse model to control the Editable Columns
28.Converts a visible column index to a column index in the model.
29.Converts a column index in the model to a visible column index
30.Returns the visible columns in the order that they appear in the model
31.Appending a Column to a JTable Component using DefaultTableModel
32.Add a column with values.
33.Disable autoCreateColumnsFromModel
34.Add a column without affecting existing columns
35.Remove the first visible column without removing the underlying data
36.Sharing a Table Model Between JTable Components
37.Creating simple JTable using AbstractTableModel
38.Map TableModel
39.TableSorter extends AbstractTableModel
40.TableSorter is a decorator for TableModels
41.Bean Property Table Model
42.A simple extension of JTable that supports the use of a SortableTableModel.
43.This program shows how to build a table from a table modelThis program shows how to build a table from a table model