使用Swing timer实现Jtable数据定时更新

框架类SuperTableFrame.java,如下:

package supertable.swing;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableModel;

import javax.swing.Action;
import javax.swing.AbstractAction;
import javax.swing.Timer;

/**
* @author Administrator
*
*/
public class SuperTableFrame extends JFrame {
private JTable table = null;
private Timer timer = null;
public SuperTableFrame(){
timer = new Timer(300,updateTableAction);
setTitle("SuperTable");
setSize(300,200);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
TableModel model = new SuperTableModel(30,5,10);
table = new JTable(model);

JPanel p = new JPanel();
addButton(p,"Update",new ActionListener(){
public void actionPerformed(ActionEvent evt){
table.validate();
table.updateUI();
}
});
addButton(p,"Start",new ActionListener(){
public void actionPerformed(ActionEvent evt){
timer.start();
}
});
addButton(p,"Stop",new ActionListener(){
public void actionPerformed(ActionEvent evt){
timer.stop();
}
});
Container contentPane = getContentPane();
contentPane.add(new JScrollPane(table),"Center");
contentPane.add(p,"South");
}
public void addButton(Container c,String title,ActionListener a){
JButton b = new JButton(title);
c.add(b);
b.addActionListener(a);
}
private Action updateTableAction = new AbstractAction(){
public void actionPerformed(ActionEvent e){
table.validate();
table.updateUI();
}
};
}


数据模板类SuperTableModel.java,如下:

package supertable.swing;

import java.text.NumberFormat;

import javax.swing.table.AbstractTableModel;
public class SuperTableModel extends AbstractTableModel {
private int years;
private int minRate;
private int maxRate;
private static final double INITAL_BALANCE = 100000.0;
public SuperTableModel(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 = INITAL_BALANCE * Math.pow(1+rate,nperiods);

double rate = Math.random();
return NumberFormat.getCurrencyInstance().format(rate);
}
public String getColumnName(int c){
double rate = (c+minRate)/100.0;
return NumberFormat.getPercentInstance().format(rate);
}
}

运行图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值