package tableModel;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
/**
* This program shows how to build a table from a table model.
* @version 1.03 2006-05-10
* @author Cay Horstmann
*/
public class InvestmentTable
{
public static void main(String[] args)
{
EventQueue.invokeLater(() ->
{
JFrame frame = new InvestmentTableFrame();
frame.setTitle("InvestmentTable");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
/**
* This frame contains the investment table.
*/
class InvestmentTableFrame extends JFrame
{
public InvestmentTableFrame()
{
TableModel model = new InvestmentTableModel(30, 5, 10);
JTable table = new JTable(model);
add(new JScrollPane(table));
pack();
}
}
/**
* This table model computes the cell entries each time they are requested. The table contents shows
* the growth of an investment for a number of years under different interest rates.
*/
class InvestmentTableModel extends AbstractTableModel
{
private static double INITIAL_BALANCE = 100000.0;
private int years;
private int minRate;
private int maxRate;
/**
* Constructs an investment table model.
* @param y the number of years
* @param r1 the lowest interest rate to tabulate
* @param r2 the highest interest rate to tabulate
*/
public InvestmentTableModel(int y, int r1, int r2)
{
years = y;
minRate = r1;
maxRate = r2;
}
public int getRowCount()
{
return years;
}
public int getColumnCount()
{
return maxRate - minRate + 1;
}
public Object getValueAt(int r, int c)
{
double rate = (c + minRate) / 100.0;
int nperiods = r;
double futureBalance = INITIAL_BALANCE * Math.pow(1 + rate, nperiods);
return String.format("%.2f", futureBalance);
}
public String getColumnName(int c)
{
return (c + minRate) + "%";
}
}
此程序清单的主函数是对一个JFrame,
InvestmentTableFrame类是一个扩展了JFrame的类,
该类只有一个函数即构造函数。
还构造函数首先构造一个InvestmentTableModel,使用这个model构造一个JTable,将这个JTable放到一个JScrollPane里,将这个JScrollPane放到JFrame中,
接下来的是一个扩展了AbstractTableModel类的表格模型InvestmentTableModel
此表模型在每次请求单元格项时计算它们。这个表格的内容显示了在不同利率下一项投资多年来的增长情况。
该类的私有字段为:
一个静态的字段INITIAL_BALANCE=100000.0;
静态字段years、minRate、maxRate。
接下来的是一个构造函数,对所有的私有元素进行赋值,
该模型对函数getRowCount、getColumnCount和getValueAt、getColumnName进行了重写,其中最关键的是方法getValueAt对表格中的值进行计算(也可以称之为初始化),getColumnName方法返回的是列名(用于初始化列名)。