java的jtable
以下是一個小程序,參考下
import javax.swing.*;
import javax.swing.table.JTableHeader;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class Test extends JFrame{
// 定義組件
private JScrollPane scpDemo;
private JTableHeader jth;
private JTable tabDemo;
private JButton btnShow;
// 構造方法
public Test(){
// 窗體的相關屬性的定義
super("JTable數據綁定示例");
this.setSize(330,400);
this.setLayout(null);
this.setLocation(100,50);
// 創建組件
this.scpDemo = new JScrollPane();
this.scpDemo.setBounds(10,50,300,270);
this.btnShow = new JButton("顯示數據");
this.btnShow.setBounds(10,10,300,30);
// 給按鈕注冊監聽
this.btnShow.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
btnShow_ActionPerformed(ae);
}
});
// 將組件加入到窗體中
add(this.scpDemo);
add(this.btnShow);
// 顯示窗體
this.setVisible(true);
}
// 點擊按鈕時的事件處理
public void btnShow_ActionPerformed(ActionEvent ae){
// 以下是連接數據源和顯示數據的具體處理方法,請注意下
try{
// 獲得連接
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:localServer","sa","");
// 建立查詢條件
String sql = "select * from localServer";
PreparedStatement pstm = conn.prepareStatement(sql);
// 執行查詢
ResultSet rs = pstm.executeQuery();
// 計算有多少條記錄
int count = 0;
while(rs.next()){
count++;
}
rs = pstm.executeQuery();
// 將查詢獲得的記錄數據,轉換成適合生成JTable的數據形式
Object[][] info = new Object[count][4];
count = 0;
while(rs.next()){
info[count][0] = Integer.valueOf( rs.getInt("id"));
info[count][1] = rs.getString("name");
info[count][2] = Integer.valueOf( rs.getInt("age") );
info[count][3] = rs.getString("sex");
count++;
}
// 定義表頭
String[] title = {"學號","姓名","年齡","性別"};
// 創建JTable
this.tabDemo = new JTable(info,title);
// 顯示表頭
this.jth = this.tabDemo.getTableHeader();
// 將JTable加入到帶滾動條的面板中
this.scpDemo.getViewport().add(tabDemo);
}catch(ClassNotFoundException cnfe){
JOptionPane.showMessageDialog(null,"數據源錯誤","錯誤",JOptionPane.ERROR_MESSAGE);
}catch(SQLException sqle){
JOptionPane.showMessageDialog(null,"數據操作錯誤","錯誤",JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args){
new Test();
}
}