日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

一个详细的JTable使用例子

發布時間:2024/1/23 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 一个详细的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.javaeye.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 (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方法是使增加或修改值的時候生效,aValue就是你在單元格填的值,
* 要把這些值保存到數據源中
*/
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添加一個監聽,當修改的時候將觸發該事件,代表事件的類是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() {
?? /**
?? * 點該按鈕的時候調用addProduct()方法,在數據源(listProduct)將
?? * 增加一個元素,沒設值前都是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,"請選擇要刪除的行!");
???? }

??? });
??? 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();
?? //如果有修改過就調用update方法
?? if(changeList.size()>0){
??? dao.update(changeList);
??? changeList.clear();
?? }
?? List newRow=getModel().getNewRow();
?? //如果是新增就調用saveList,支持一次增加多行
??????? if(newRow.size()>0){
??? dao.saveList(newRow);
??? getModel().setList(dao.getList());
??? getTable().updateUI();
??? newRow.clear();
??????? }
??
}
public void deleteProduct() {
?? /**支持一次刪除多行,先獲得所有選中的行,然后按照行數取得Product實例,
?? * 放進一個list,然后傳給操作數據庫的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() {
?? /**
?? * 初始化數據源,從數據庫里把數據拿出來,然后它會調用
?? * getValueAt方法來一個單元格一個單元格來設值,讓它顯示出來.
?? */
?? 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("裝載驅動出錯!");
?? } catch (SQLException e) {
??? System.out.println("獲取數據庫連接出錯!");
??? 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("取出全部數據出錯!");
??? JOptionPane.showMessageDialog(null, "取出全部數據出錯!");
??? 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, "取出全部數據出錯!");
??? e.printStackTrace();
?? } finally {
??? try {
???? rs.close();
???? ps.close();
???? conn.close();
??? } catch (SQLException e) {
???? JOptionPane.showMessageDialog(null, "關閉數據連接時出錯!");
???? 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("添加數據時出錯!");
??? JOptionPane.showMessageDialog(null, "添加數據時出錯!");
??? e.printStackTrace();
?? } finally {
??? try {
???? ps.close();
???? conn.close();
??? } catch (SQLException e) {
???? JOptionPane.showMessageDialog(null, "關閉數據連接時出錯!");
???? 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, "關閉數據連接時出錯!");
???? 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, "修改數據時出錯!");
??? e.printStackTrace();
?? } finally {
??? try {
???? ps.close();
???? conn.close();
??? } catch (SQLException e) {
???? JOptionPane.showMessageDialog(null, "關閉數據連接時出錯!");
???? 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
*/
/**
* 監聽table被改動的事件,只要目的是用來記錄被修改過的值,
* 這樣做可以一次任意行的修改值,修改一個單元格的值就記錄一次,
* 主要記錄id,新值,烈數.
*/
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);
??? }
?? }
}

}

總結

以上是生活随笔為你收集整理的一个详细的JTable使用例子的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。