import java.sql.*;import java.awt.*;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;import javax.swing.*;public class ASFrame extendsJFrame{private static final int DEFAULT_WEIDTH = 400;private static final int DEFAULT_HEIGHT = 680;privateJScrollPane scpDemo;privateJTable tabDemo;privateJScrollPane scpDemo1;privateJTable tabDemo1;publicASFrame()
{
JFrame f=newJFrame();
f.setTitle("通讯录");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(DEFAULT_WEIDTH, DEFAULT_HEIGHT);
f.setVisible(true);
f.setResizable(false);
f.setLayout(null);
JLabel label1= new JLabel("联系人");
f.add(label1);
label1.setFont(new Font("宋体",1,30));
label1.setBounds(150, 30, 100, 40);this.scpDemo = newJScrollPane();this.scpDemo.setBounds(40,110,320,500);try{
btnShow();
}catch (InstantiationException |IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}//将组件加入到窗体中
f.add(this.scpDemo);
}public void btnShow() throwsInstantiationException, IllegalAccessException{
String sql= "select * from Address";try{//获得连接
Class.forName("com.hxtt.sql.access.AccessDriver").newInstance();
Connection conn= DriverManager.getConnection("jdbc:Access:///C:/Users/k05/Desktop/Address.mdb","","");
PreparedStatement pstm=conn.prepareStatement(sql);
ResultSet rs=pstm.executeQuery(sql);//计算有多少条记录
int count = 0;while(rs.next()){
count++;
}
rs=pstm.executeQuery();//将查询获得的记录数据,转换成适合生成JTable的数据形式
Object[][] info = new Object[count][2];
count= 0;while(rs.next()){
info[count][0] = rs.getString("name");
info[count][1] = rs.getString("phonenumber");
count++;
}//定义表头
String[] title = {"姓名","电话号码"};//创建JTable
this.tabDemo = newJTable(info,title);//显示表头//this.jth = this.tabDemo.getTableHeader();//将JTable加入到带滚动条的面板中
this.scpDemo.getViewport().add(tabDemo);
rs.close();
conn.close();
}catch(ClassNotFoundException cnfe){
JOptionPane.showMessageDialog(null,"数据源错误","错误",JOptionPane.ERROR_MESSAGE);
}catch(SQLException sqle){
JOptionPane.showMessageDialog(null,"数据操作错误","错误",JOptionPane.ERROR_MESSAGE);
}
}
}