//列子1:简单
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Table extends JFrame {
private JTable table;
public static void main(String args[]) {
try {
Table frame = new Table();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public Table() {
super();
getContentPane_r().setLayout(null);
setBounds(100, 100, 500, 375);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(55, 65, 340, 174);
getContentPane_r().add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
//
this.CreatTable();
}
private void CreatTable(){
DefaultTableModel dtm = new DefaultTableModel();
Vector Title = new Vector();
//添加标题
Title.add( "姓名 ");
Title.add( "性别 ");
Title.add( "爱好 ");
Vector c1 = new Vector();
//添加第一条内容
c1.add( "西门庆 ");
c1.add( "男 ");
c1.add( "SM ");
Vector c2 = new Vector();
//添加第二条内容
c2.add( "潘金莲 ");
c2.add( "女 ");
c2.add( "ML ");
Vector Main = new Vector();
Main.add(c1);
Main.add(c2);
dtm.setDataVector(Main, Title);
table.setModel(dtm);
}
}
//2.列子 带数据库
//是连接SQLServer的pubs数据库的authors表的.我用odbc驱动,数据源是pubs.
import javax.swing.*;
import java.sql.*;
class SqlDemo2 extends JFrame{
SqlDemo2(){
try{
String[] colHeads={ "name ", "Phone ", "City "};
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver ");
String url= "jdbc:odbc:pubs ";
Connection con=DriverManager. getConnection_r(url, "sa ", " ");
Statement stmt=con.createStatement();
ResultSet rs;
rs=stmt.executeQuery( "SELECT count(*) as au_count from authors ");
rs.next();
int iCount=rs. getInt_r( "au_count ");
Object[][] data=new Object[iCount][];
int i=0;
rs=stmt.executeQuery( "SELECT * from authors ");
while(rs.next()){
data[i]=new Object[3];
data[i][0]=rs. getString_r( "au_fname ");
data[i][1]=rs. getString_r( "Phone ");
data[i][2]=rs. getString_r( "City ");
i++;
}
JTable table=new JTable(data,colHeads);
JScrollPane jsp=new JScrollPane(table);
this. getContentPane_r().add(jsp);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
catch(Exception e){
System.out.println(e);
}
}
public static void main(String[] args){
SqlDemo2 sd=new SqlDemo2();
sd.setSize(400,250);
sd.setVisible(true);
}
}