一个详细的JTable使用例子
最近需要使用JTable,第一次使用,很多不懂,到網(wǎng)上找了很多資料和例子,發(fā)現(xiàn)很多例子都沒有完全的實(shí)現(xiàn)操作數(shù)據(jù)庫里一張表的數(shù)據(jù),摸了兩天終于懂了一點(diǎn),寫了一個(gè)例子,把代碼直接復(fù)制,修改一下數(shù)據(jù)庫的連接就可以運(yùn)行了.使用JTable操作數(shù)據(jù)庫的一張表,實(shí)現(xiàn)增刪改,顯示表里所有的數(shù)據(jù),點(diǎn)擊''添加''按鈕在表格插入一行填寫數(shù)據(jù)保存到數(shù)據(jù)庫,可一次插入多行,一次可選擇任意多行進(jìn)行刪除,一次可以修改多行的值.有寫得不好的地方希望大家指出,一起進(jìn)步.
共九個(gè)類:
一:
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.javaeye.com
*/
/**changeList用來存放被修改過的數(shù)據(jù)值,這樣做是為了一次修改多行多值,
* 保存的對象是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方法就是使得數(shù)據(jù)在Table顯示出來,給每個(gè)單元格設(shè)值
*/
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 (col) {
?? case 1:
??? p.setProduct_name(value);
??? break;
?? case 2:
??? p.setProduct_desc(value);
??? break;
?? case 3:
??? p.setProduct_status(value);
??? break;
?? }
?? fireTableDataChanged();
}
public boolean isCellEditable(int row, int column) {
?? return true;
}
/**
* setValueAt方法是使增加或修改值的時(shí)候生效,aValue就是你在單元格填的值,
* 要把這些值保存到數(shù)據(jù)源中
*/
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
?? ProductBean p = (ProductBean) list.get(rowIndex);
?? setPropertyValueByCol(p, aValue.toString(), columnIndex);
?? this.fireTableCellUpdated(rowIndex, columnIndex);
}
public static List getChangeList() {
?? return changeList;
}
public static void setChangeList(List changeList) {
?? ProductTableModel.changeList = changeList;
}
}
二:
package product;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableColumnModel;
public class ProductFrame extends JFrame {
/**
* 神戀科技:http://suhuanxi.javaeye.com
*/
private JPanel panelTop = null;
private JLabel labHeader = null;
private JPanel panelBottom = null;
private JButton add = null;
private JButton delete = null;
private JButton save = null;
private JScrollPane scroll = null;
private JTable table = null;
private ProductTableModel model = null;
private List listProduct = null;
public ProductTableModel getModel() {
?? if (null == model) {
??? model = new ProductTableModel(listProduct);
??? //給model添加一個(gè)監(jiān)聽,當(dāng)修改的時(shí)候?qū)⒂|發(fā)該事件,代表事件的類是ChangeEvent
??? model.addTableModelListener(new ChangeEvent(model));
??? return model;
?? }
?? return model;
}
public JLabel getLabHeader() {
?? if (null == labHeader) {
??? labHeader = new JLabel("Maintaince Product Information");
??? return labHeader;
?? }
?? return labHeader;
}
public JTable getTable() {
?? if (null == table) {
??? table = new JTable(getModel());
??? table.setEnabled(true);
??? table.setRowSelectionAllowed(true);
??? table.setBackground(Color.YELLOW);
??? /**
??? * 隱藏第一列ID,不顯示出來
??? */
??? DefaultTableColumnModel dcm = (DefaultTableColumnModel)table.getColumnModel();
????? dcm.getColumn(0).setMinWidth(0);
????? dcm.getColumn(0).setMaxWidth(0); ????
??? return table;
?? }
?? return table;
}
public JScrollPane getPanTable() {
?? if (null == scroll) {
??? scroll = new JScrollPane();
??? scroll.setViewportView(getTable());
??? return scroll;
?? }
?? return scroll;
}
public JPanel getPanelTop() {
?? if (null == panelTop) {
??? panelTop = new JPanel();
??? panelTop.setLayout(new FlowLayout(FlowLayout.CENTER));
??? panelTop.add(getLabHeader());
??? return panelTop;
?? }
?? return panelTop;
}
public JPanel getPanelBottom() {
?? if (null == panelBottom) {
??? panelBottom = new JPanel();
??? panelBottom.setLayout(new FlowLayout(FlowLayout.CENTER));
??? panelBottom.add(getAdd());
??? panelBottom.add(getDelete());
??? panelBottom.add(getSave());
??? return panelBottom;
?? }
?? return panelBottom;
}
public JButton getAdd() {
?? /**
?? * 點(diǎn)該按鈕的時(shí)候調(diào)用addProduct()方法,在數(shù)據(jù)源(listProduct)將
?? * 增加一個(gè)元素,沒設(shè)值前都是null.
?? */
?? if (null == add) {
??? add = new JButton("New");
??? add.addActionListener(new ActionListener() {
???? public void actionPerformed(ActionEvent e) {
????? addProduct();??
???? }
??? });
??? return add;
?? }
?? return add;
}
public JButton getDelete() {
?? if (null == delete) {
??? delete = new JButton("Delete");
??? delete.addActionListener(new ActionListener() {
???? public void actionPerformed(ActionEvent e) {
????? /**
????? * 支持一次選中多行后刪除
????? */
????? int[] rows=getTable().getSelectedRows();
????? if(rows.length>0){
????? int flag=JOptionPane.showConfirmDialog(null, "確定刪除?");
????? if(flag==JOptionPane.YES_OPTION)
????? deleteProduct();
????? }
????? else
?????? JOptionPane.showMessageDialog(null,"請選擇要?jiǎng)h除的行!");
???? }
??? });
??? return delete;
?? }
?? return delete;
}
public JButton getSave() {
?? if (null == save) {
??? save = new JButton("save");
??? save.addActionListener(new ActionListener() {
???? public void actionPerformed(ActionEvent e) {
????? saveProduct();
????? JOptionPane.showMessageDialog(null,"更新成功!");
???? }
??? });
??? return save;
?? }
?? return save;
}
public void addProduct() {
?? ProductBean p = new ProductBean();
?? getModel().addRow(getTable().getSelectedRow(), p);
}
public void saveProduct() {
?? DaoInterface dao=DaoFactory.getDao();
?? List changeList=getModel().getChangeList();
?? //如果有修改過就調(diào)用update方法
?? if(changeList.size()>0){
??? dao.update(changeList);
??? changeList.clear();
?? }
?? List newRow=getModel().getNewRow();
?? //如果是新增就調(diào)用saveList,支持一次增加多行
??????? if(newRow.size()>0){
??? dao.saveList(newRow);
??? getModel().setList(dao.getList());
??? getTable().updateUI();
??? newRow.clear();
??????? }
??
}
public void deleteProduct() {
?? /**支持一次刪除多行,先獲得所有選中的行,然后按照行數(shù)取得Product實(shí)例,
?? * 放進(jìn)一個(gè)list,然后傳給操作數(shù)據(jù)庫的deleteList方法.
?? */
?? int[] rows=getTable().getSelectedRows();
?? ArrayList list=new ArrayList();
?? DaoInterface dao=DaoFactory.getDao();
?? for(int i=rows.length-1;i>=0;i--){
?? list.add(getModel().getRow(rows[i]));
?? getModel().deleteRow(rows[i]);
?? }
?? dao.deleteList(list);
?? getTable().updateUI();
?? list.clear();
}
public void initData() {
?? /**
?? * 初始化數(shù)據(jù)源,從數(shù)據(jù)庫里把數(shù)據(jù)拿出來,然后它會調(diào)用
?? * getValueAt方法來一個(gè)單元格一個(gè)單元格來設(shè)值,讓它顯示出來.
?? */
?? listProduct = new ArrayList();
???? DaoInterface dao=DaoFactory.getDao();
???? listProduct=dao.getList();
?? this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public ProductFrame() {
?? initData();
?? Container c = this.getContentPane();
?? c.setLayout(new BorderLayout());
?? c.add(getPanelTop(), BorderLayout.NORTH);
?? c.add(getPanelBottom(), BorderLayout.SOUTH);
?? c.add(getPanTable(), BorderLayout.CENTER);
?? this.setSize(new Dimension(600, 400));
?? this.setVisible(true);
}
public static void main(String[] args) {
?? ProductFrame frame = new ProductFrame();
?? frame.addWindowListener(new WindowAdapter() {
??? public void windowClosing(WindowEvent e) {
???? System.exit(0);
??? }
?? });
}
???
}
三:
package product;
public class ProductBean {
/**
* 神戀科技:http://suhuanxi.javaeye.com
*/
private int product_id;
private String product_name;
private String product_desc;
private String product_status;
public String getProduct_name() {
?? return product_name;
}
public void setProduct_name(String product_name) {
?? this.product_name = product_name;
}
public String getProduct_desc() {
?? return product_desc;
}
public void setProduct_desc(String product_desc) {
?? this.product_desc = product_desc;
}
public String getProduct_status() {
?? return product_status;
}
public void setProduct_status(String product_status) {
?? this.product_status = product_status;
}
public int getProduct_id() {
?? return product_id;
}
public void setProduct_id(int product_id) {
?? this.product_id = product_id;
}
}
四:
package product;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBConnection {
/**
* 神戀科技:http://suhuanxi.javaeye.com
*/
private static Connection conn;
public static Connection getConn() {
?? String driverName = "oracle.jdbc.driver.OracleDriver";
?? String url = "jdbc:oracle:thin:@192.168.0.66:1521:test";
?? String userName = "JACKTRAINING";
?? String pwd = "JACKTRAINING";
?? try {
??? Class.forName(driverName);
??? conn = DriverManager.getConnection(url, userName, pwd);
?? } catch (ClassNotFoundException e) {
??? System.out.println("裝載驅(qū)動(dòng)出錯(cuò)!");
?? } catch (SQLException e) {
??? System.out.println("獲取數(shù)據(jù)庫連接出錯(cuò)!");
??? e.printStackTrace();
?? }
?? return conn;
}
}
五:
package product;
import java.util.ArrayList;
import java.util.List;
public interface DaoInterface {
/**
* 神戀科技:http://suhuanxi.javaeye.com
*/
public List getList();
public void saveList(List list);
public void deleteList(List list);
public void update(List list);
}
六:
package product;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
public class DaoImpl implements DaoInterface {
/**
* 神戀科技:http://suhuanxi.javaeye.com
*/
public List getList() {
?? Connection conn = JDBConnection.getConn();
?? String s1 = "select * from justin_jtable_product order by product_id asc";
?? PreparedStatement ps = null;
?? ResultSet rs = null;
?? List list = new ArrayList();
?? try {
??? ps = conn.prepareStatement(s1);
??? rs = ps.executeQuery();
?? } catch (SQLException e) {
??? System.out.println("取出全部數(shù)據(jù)出錯(cuò)!");
??? JOptionPane.showMessageDialog(null, "取出全部數(shù)據(jù)出錯(cuò)!");
??? e.printStackTrace();
?? }
?? try {
??? while (rs.next()) {
???? ProductBean p = new ProductBean();
???? p.setProduct_id(rs.getInt(1));
???? p.setProduct_name(rs.getString(2));
???? p.setProduct_desc(rs.getString(3));
???? p.setProduct_status(rs.getString(4));
???? list.add(p);
??? }
?? } catch (SQLException e) {
??? JOptionPane.showMessageDialog(null, "取出全部數(shù)據(jù)出錯(cuò)!");
??? e.printStackTrace();
?? } finally {
??? try {
???? rs.close();
???? ps.close();
???? conn.close();
??? } catch (SQLException e) {
???? JOptionPane.showMessageDialog(null, "關(guān)閉數(shù)據(jù)連接時(shí)出錯(cuò)!");
???? e.printStackTrace();
??? }
?? }
?? return list;
}
public void saveList(List list) {
?? String s1 = "";
?? Connection conn = JDBConnection.getConn();
?? PreparedStatement ps = null;
?? try {
??? Iterator it = list.iterator();
??? while (it.hasNext()) {
???? ProductBean p = (ProductBean) it.next();
???? String name = p.getProduct_name();
???? String desc = p.getProduct_name();
???? String status = p.getProduct_status();
???? int id = p.getProduct_id();
???? s1 = "insert into justin_jtable_product(product_name,"
?????? + "product_desc,product_status) values(?,?,?)";
???? ps = conn.prepareStatement(s1);
???? ps.setString(1, name);
???? ps.setString(2, desc);
???? ps.setString(3, status);
???? ps.executeUpdate();
??? }
?? } catch (SQLException e) {
??? System.out.println("添加數(shù)據(jù)時(shí)出錯(cuò)!");
??? JOptionPane.showMessageDialog(null, "添加數(shù)據(jù)時(shí)出錯(cuò)!");
??? e.printStackTrace();
?? } finally {
??? try {
???? ps.close();
???? conn.close();
??? } catch (SQLException e) {
???? JOptionPane.showMessageDialog(null, "關(guān)閉數(shù)據(jù)連接時(shí)出錯(cuò)!");
???? e.printStackTrace();
??? }
?? }
}
public void deleteList(List list) {
?? String str = "delete from justin_jtable_product where product_id=?";
?? int id = 0;
?? Iterator it = list.iterator();
?? Connection conn = JDBConnection.getConn();
?? PreparedStatement ps = null;
?? try {
??? while (it.hasNext()) {
???? id = ((ProductBean) it.next()).getProduct_id();
???? ps = conn.prepareStatement(str);
???? ps.setInt(1, id);
???? ps.executeUpdate();
??? }
?? } catch (SQLException e) {
?? } finally {
??? try {
???? ps.close();
???? conn.close();
??? } catch (SQLException e) {
???? JOptionPane.showMessageDialog(null, "關(guān)閉數(shù)據(jù)連接時(shí)出錯(cuò)!");
???? e.printStackTrace();
??? }
?? }
}
public void update(List list) {
?? Connection conn = JDBConnection.getConn();
?? PreparedStatement ps = null;
?? Iterator it = list.iterator();
?? int id = 0;
?? int col = 0;
?? String value = "";
?? String str = "";
?? try {
??? while (it.hasNext()) {
???? ChangedProduct ch = (ChangedProduct) it.next();
???? id = ch.getId();
???? col = ch.getCol();
???? value = ch.getValue();
???? switch (col) {
???? case 1:
????? str = "update justin_jtable_product set product_name=? where product_id=?";
????? break;
???? case 2:
????? str = "update justin_jtable_product set product_desc=? where product_id=?";
????? break;
???? case 3:
????? str = "update justin_jtable_product set product_status=? where product_id=?";
???? }
???? ps = conn.prepareStatement(str);
???? ps.setString(1, value);
???? ps.setInt(2, id);
???? ps.executeUpdate();
??? }
?? } catch (SQLException e) {
??? JOptionPane.showMessageDialog(null, "修改數(shù)據(jù)時(shí)出錯(cuò)!");
??? e.printStackTrace();
?? } finally {
??? try {
???? ps.close();
???? conn.close();
??? } catch (SQLException e) {
???? JOptionPane.showMessageDialog(null, "關(guān)閉數(shù)據(jù)連接時(shí)出錯(cuò)!");
???? e.printStackTrace();
??? }
?? }
}
}
七:
package product;
public class DaoFactory {
/**
* 神戀科技:http://suhuanxi.javaeye.com
*/
synchronized public static DaoInterface getDao(){
DaoInterface dao=null;
if(dao==null){
dao=new DaoImpl();
return dao;
}
return dao;
}
}
八:
package product;
public class ChangedProduct {
/**
* 神戀科技:http://suhuanxi.javaeye.com
*/
private int id;
private int col;
private String value;
public int getId() {
?? return id;
}
public void setId(int id) {
?? this.id = id;
}
public String getValue() {
?? return value;
}
public void setValue(String value) {
?? this.value = value;
}
public int getCol() {
?? return col;
}
public void setCol(int col) {
?? this.col = col;
}
}
九:
package product;
import java.util.ArrayList;
import java.util.List;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
public class ChangeEvent implements TableModelListener {
/**
* 神戀科技:http://suhuanxi.javaeye.com
*/
/**
* 監(jiān)聽table被改動(dòng)的事件,只要目的是用來記錄被修改過的值,
* 這樣做可以一次任意行的修改值,修改一個(gè)單元格的值就記錄一次,
* 主要記錄id,新值,烈數(shù).
*/
ProductTableModel model = null;
public ChangeEvent(ProductTableModel model) {
?? this.model = model;
}
List list = model.getChangeList();
int id = 0;
String value = "";
public void tableChanged(TableModelEvent arg0) {
?? int row = arg0.getFirstRow();
?? int col = arg0.getColumn();
?? if (col != -1) {
??? ChangedProduct cp = new ChangedProduct();
??? id = ((Integer) model.getValueAt(row, 0)).intValue();
??? if (id != 0) {
???? value = model.getValueAt(row, col).toString();
???? cp.setId(id);
???? cp.setCol(col);
???? cp.setValue(value);
???? list.add(cp);
??? }
?? }
}
}
總結(jié)
以上是生活随笔為你收集整理的一个详细的JTable使用例子的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 修改Jtable字体颜色
- 下一篇: Android对话框dialog大全(代