日期:2014-05-16  浏览次数:20511 次

JTable操作数据库的例子

最近需要使用JTable,第一次使用,很多不懂,到网上找了很多资料和例子,发现很多例子都没有完全的实现操作数据库里一张表的数据,摸了两天终于懂了一点,写了一个例子,把代码直接复制,修改一下数据库的连接就可以运行了.使用JTable操作数据库的一张表,实现增删改,显示表里所有的数据,点击''添加''按钮在表格插入一行填写数据保存到数据库,可一次插入多行,一次可选择任意多行进行删除,一次可以修改多行的值.有写得不好的地方希望大家指出,一起进步.

共九个类:

一:

package product;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.table.AbstractTableModel;

public class ProductTableModel extends AbstractTableModel {


?/**
? * 神恋科技:http://suhuanxi.iteye.com
? */
?/**changeList用来存放被修改过的数据值,这样做是为了一次修改多行多值,
? * 保存的对象是ChangedProduct,只记录被修改过的值.
? */
?private static List changeList = new ArrayList();
?private List list = new ArrayList();
?private String[] column = { "Product_id", "Product Name",
???"Product Description", "Status" };

?public ProductTableModel() {
?}

?public ProductTableModel(List list) {
??this();
??setList(list);
?}

?public int getColumnCount() {
??return column.length;
?}

?public int getRowCount() {
??return list.size();
?}
/**
?* getValueAt方法就是使得数据在Table显示出来,给每个单元格设值
?*/
?public Object getValueAt(int arg0, int arg1) {
??ProductBean p = (ProductBean) list.get(arg0);
??return getPropertyValueByCol(p, arg1);
?}

?public void addRow(int index, ProductBean p) {
??if (index < 0 || index > list.size() - 1) {
???list.add(p);
???fireTableRowsInserted(list.size(), list.size());
??} else {
???list.add(index + 1, p);
???fireTableRowsInserted(index, index);
??}
?}

?public boolean deleteRow(int index) {
??if (index >= 0 && index < list.size()) {
???list.remove(index);
???fireTableRowsDeleted(index, index);
???return true;
??} else
???return false;
?}

?public boolean saveRow(int index, ProductBean p) {
??if (index >= 0 && index < list.size()) {
???list.set(index, p);
???fireTableRowsUpdated(index, index);
???return true;
??} else
???return false;
?}

?public ProductBean getRow(int index) {
??if (index >= 0 && index < list.size()) {
???return (ProductBean) list.get(index);

??} else
???return null;
?}
?public List getNewRow(){
??List list=new ArrayList();
??List listProduct=getList();
??Iterator it=listProduct.iterator();
??while(it.hasNext()){
???ProductBean p=new ProductBean();
???p=(ProductBean)it.next();
???if(p.getProduct_id()==0){
????list.add(p);
???}
??}
??return list;
?}

?public List getList() {
??return list;
?}

?public void setList(List list) {
??this.list = list;
??fireTableDataChanged();
?}

?public String getColumnName(int i) {
??return column[i];
?}

?public void setColumn(String[] column) {
??this.column = column;
?}

?public Object getPropertyValueByCol(ProductBean p, int col) {
??switch (col) {
??case 0:
???return p.getProduct_id();
??case 1:
???return p.getProduct_name();
??case 2:
???return p.getProduct_desc();
??case 3:
???return p.getProduct_status();
??}
??return null;
?}

?public void setPropertyValueByCol(ProductBean p, String value, int col) {
??switch (c