package text;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
public class myWork extends JFrame {
//定义组件
private JScrollPane scpDemo;
private JTableHeader jth;
private JTable tabDemo;
private JButton btnShow;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
myWork frame = new myWork();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public myWork() {
/*setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);*/
//窗体的相关属性的定义
this.setSize(300,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","mywork","");
//建立查询条件
String sql="select * from mywork";
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][6];
count=0;
while(rs.next()){
info[count][0]=Integer.valueOf(rs.getInt("Number"));
info[count][1]=rs.getString("name");
info[count][2]=rs.getString("classes");
info[count][3]=rs.getString("math");
info[count][4]=rs.getString("chinese");
info[count][5]=rs.getString("english");
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 sale){
JOptionPane.showMessageDialog(null, "数据库操作错误","错误",JOptionPane.ERROR_MESSAGE);
}
}
}