TableModel應用執行個體

來源:互聯網
上載者:User

在java核心技術看到TableModel的應用,稍微改動了一下,發覺這東西確實不錯,拿來分享一下,再挖掘挖掘.

package com.java;

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

public class tableTest {

 private static JTable table;

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  tabFrame frame = new tabFrame();
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setVisible(true);
 }
}

class tabFrame extends JFrame {
 private JTable table;

 public tabFrame() {
  setTitle("表格模型測試");
  setSize(400, 300);
  getContentPane().setLayout(null);

  final JScrollPane scrollPane = new JScrollPane();
  scrollPane.setBounds(65, 10, 255, 201);
  getContentPane().add(scrollPane);

  TableModel model = new InvestmentTableModel(30, 5, 10); //建立表格模型對象
  table = new JTable(model); //建立表格,載入表格模型
  scrollPane.setViewportView(table); //在捲動方塊中加入表格
 }
}

/**
 * 表格模型類
 */
class InvestmentTableModel extends AbstractTableModel {
 private int years;
 private int minRate;
 private int maxRate;
 private static double INITIAL_BALANCE = 100000.0;

 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 futurBalance = INITIAL_BALANCE * Math.pow(1 + rate, nperiods);
  return String.format("%.2f", futurBalance);
 }

 /**
  * 設定列名
  */
 public String getColumnName(int c) {
  return (c + minRate) + "%";
 }
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.