JTable界面的即时刷新

用JTable显示数据库中的数据是非常方便的,但有个问题是如果更新数据的话,界面上的数据依旧没有变需要重启(从数据库中取得新数据)才能显示更新后的数据。我从网上找了很多资料但都不成功,最后自已实现了一部分(说一部分成功是因为删除数据能即时更新但添加数据仍需重启,但我这里采用了一个刷新按钮来实现重新从数据库读取数据!)

下面是我做的通讯录的两个重要类,有关于界面刷新的重要部分红色显示!

public class DBManager extends AbstractTableModel{

private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
private Vector> rows = new Vector>();
private final String[] columnNames = {"姓名","性别","住址","QQ","Email","家庭电话","手机","出生日期"};

public DBManager() {
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
conn=DriverManager.getConnection("jdbc:odbc:address_book", "","");
stmt=conn.createStatement();
query("select * from person");
}
catch(SQLException e){ System.out.println(e.getMessage()); }
catch(Exception ex){ System.out.println("createError:"+ex.getMessage());}
}
public void query(String sql)
{
try{
rs=stmt.executeQuery(sql);
while (rs.next()) {
Vector newRow = new Vector();
for (int i = 1; i <= getColumnCount(); i++) {
newRow.addElement((String)rs.getObject(i+1));
}newRow.addElement(rs.getObject(1).toString());
rows.addElement(newRow);
}
fireTableChanged(null); // Tell the listeners a new table has arrived.
}
catch(SQLException e){System.out.println("executeQuery:"+e.getMessage());}

}
public void executeUpdate(String sql)
{
try{
//执行操作数据库SQL语句的方法,如插入、删除、更新记录
stmt.executeUpdate(sql);
}catch(SQLException e){ System.out.println("excecuteUpdate:"+e.getMessage());}
}
//关闭resultset、statement和connection
public void close()
{
try{
if(rs!=null) rs.close();
if(stmt!=null) stmt.close();
if(conn!=null) conn.close();
}catch(SQLException e){ System.err.println(e.getMessage());}
}

//////////////////////////////////////////////////////////////////////////
//
// Implementation of the TableModel Interface
//
//////////////////////////////////////////////////////////////////////////


public String getColumnName(int column) {
if (columnNames[column] != null) {
return columnNames[column];
}else {
return "";
}
}

public Class getColumnClass(int column) {
//return getValueAt(0, column).getClass();
return String.class;
}

public boolean isCellEditable(int row, int column) {
return true;
}

public int getColumnCount() {
return columnNames.length;
}

public int getRowCount() {
return rows.size();
}
[color=red] public void empty(){
rows.setSize(0);
fireTableDataChanged();
}[/color]


public Object getValueAt(int aRow, int aColumn) {
Vector row = (Vector)rows.elementAt(aRow);
return row.elementAt(aColumn);
}

public void setValueAt(Object value, int row, int column) {
String names[]={"name","gender","address","QQ","email","phone","tellphone","brithday"};//对应数据表中的字断列
String id=getId(row);
Vector dataRow = (Vector)rows.elementAt(row);
dataRow.setElementAt(value, column);
String query ="update person set "+names[column]+"='"+getValueAt(row,column)+ "' where id="+id;
//System.out.println(query);
executeUpdate(query);
}
public String getId(int row){
String names[]={"name","gender","address","QQ","email","phone","tellphone","brithday"};//对应数据表中的字断列
Vector dataRow = (Vector)rows.elementAt(row);
String id=(String)dataRow.elementAt(names.length);//取对该行的ID号
return id;
}

}


public class MainFrame extends JFrame implements ActionListener, MouseListener{

DBManager db=new DBManager();
JTextField queryText=new JTextField("请在此输入要查询姓名");
JButton bt_query=new JButton("查询");
JButton bt_add= new JButton("添加");
JButton bt_return=new JButton("刷新");
JButton bt_delete=new JButton("删除");
JTable tableView = new JTable();
public MainFrame() {
super("通讯录");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设定关闭窗体时退出程序
////////////////以下的程序是设置JTable的内容/////////////////////
tableView.setModel(db);
tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
setTool();


JScrollPane scrollpane = new JScrollPane(tableView);
scrollpane.setBorder(new BevelBorder(BevelBorder.LOWERED));
scrollpane.setPreferredSize(new Dimension(605, 500));
////////////////////////////////////////////////
JPanel top=new JPanel();
top.add(queryText);
top.add(bt_query);
JPanel bottom=new JPanel();
bottom.add(bt_add);
bottom.add(bt_return);
bottom.add(bt_delete);

JPanel pane=new JPanel();
pane.setLayout(new BorderLayout());
pane.add(top,BorderLayout.NORTH);
pane.add(scrollpane,BorderLayout.CENTER);
pane.add(bottom,BorderLayout.SOUTH);
//////////////////////////////////////////////////
bt_delete.addActionListener(this);
bt_add.addActionListener(this);
bt_query.addActionListener(this);
bt_return.addActionListener(this);
queryText.addMouseListener(this);

getContentPane().add(pane);
pack();
setVisible(true); setResizable(false);
setLocationRelativeTo(null);//设置位置居屏幕中央
}
public void setTool(){
JComboBox comboBox = new JComboBox();
comboBox.addItem("男");
comboBox.addItem("女");

TableColumn colorColumn = tableView.getColumn("性别");
colorColumn.setCellEditor(new DefaultCellEditor(comboBox));

DefaultTableCellRenderer colorColumnRenderer = new DefaultTableCellRenderer();
colorColumnRenderer.setBackground(Color.pink);
colorColumnRenderer.setToolTipText("Click for combo box");
colorColumn.setCellRenderer(colorColumnRenderer);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==bt_delete){
int i=tableView.getSelectedRow();
if(i>=0){
String id=db.getId(i);
db.executeUpdate("delete * from person where id="+id);
}
[color=red] db.empty();
db.query("select * from person");setTool();[/color]
}
else if(e.getSource()==bt_add){
NewPerson np=new NewPerson();
np.setVisible(true);
}
else if(e.getSource()==bt_query){
[color=red] db.empty();
String a=queryText.getText();
db.query("select * from person where name like'%"+a+"%'");setTool();[/color] }
else if(e.getSource()==bt_return){
[color=red]db.empty();
db.query("select * from person");
setTool();[/color] }
}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseClicked(MouseEvent e){queryText.setText("");}

public static void main(String[] args) {
new MainFrame();
}

}

你可能感兴趣的:(JTable界面的即时刷新)