M V C principle
Java Swing JTable Usefull
=======================
Object Class User
=======================
/**
*
Title:
*
*
Description:
*
*
Copyright: Copyright (c) 2007
*
*
Company:
*
* @author not attributable
* @version 1.0
*/
public class User {
private int userID;
private String userName;
private String userSex;
private int userAge;
public User() {
}
public void setUserID(int userID) {
this.userID = userID;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
public int getUserID() {
return userID;
}
public String getUserName() {
return userName;
}
public String getUserSex() {
return userSex;
}
public int getUserAge() {
return userAge;
}
public Object[] getUserInfoToArray() {
return new Object[] {userID, userName, userSex, userAge};
}
}
============================
Model Class Control JTable
============================
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.*;
/**
*
Title:
*
*
Description:
*
*
Copyright: Copyright (c) 2007
*
*
Company:
*
* @author not attributable
* @version 1.0
*/
public class UserModel extends AbstractTableModel {
String[] column = {"用户编号", "用户姓名", "用户性别", "用户年龄"};
ArrayList UserList = new ArrayList();
public UserModel() {
fillInfoInJtable();
}
public int getRowCount() {
return UserList.size();
}
public int getColumnCount() {
return column.length;
}
public String getColumnName(int Index) {
return column[Index];
}
public Object getValueAt(int rowIndex, int columnIndex) {
User user = (User) UserList.get(rowIndex);
Object[] obj = user.getUserInfoToArray();
return obj[columnIndex];
}
public void fillInfoInJtable() {
Connection con = DB.getConnection();
try {
Statement stmt = con.createStatement();
String sql = "select * from UserTable";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
User user = new User();
user.setUserID(rs.getInt("UserID"));
user.setUserName(rs.getString("UserName"));
user.setUserSex(rs.getString("UserSex"));
user.setUserAge(rs.getInt("UserAge"));
UserList.add(user);
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException ex1) {
}
}
}
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10395457/viewspace-927174/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/10395457/viewspace-927174/