-
查詢所有用戶的二維表界面
查詢所有用戶 - 代碼
import javax.swing.*;
import javax.swing.table.JTableHeader;
import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class userTableInfo extends JFrame{
// 定義組件
private JScrollPane scpDemo;
private JTableHeader jth;
private JTable tabDemo;
private JButton btnShow;
// JFrame jf = new JFrame("顯示所有用戶信息");
public static void main(String[] args){
new userTableInfo();
}
// 構(gòu)造方法
public userTableInfo(){
// 窗體的相關(guān)屬性的定義
//必須要創(chuàng)建一個JFrame對象,才可以在function函數(shù)中調(diào)用這個類!!!
//之前其實已經(jīng)調(diào)用了這個類,只是沒有調(diào)用到JFrame??!所以顯示不出來
//設(shè)置面板透明
//.setOpaque(false);
this.setSize(600,400);
this.setLayout(null);
this.setLocation(1220,200);
// 創(chuàng)建組件
this.scpDemo = new JScrollPane();
//顯示框
this.scpDemo.setBounds(0,100,600,400);
//按鈕
this.btnShow = new JButton("點擊刷新并顯示數(shù)據(jù)");
btnShow.setFont(new Font("楷體", NORMAL, 25));
btnShow.setBackground(Color.pink);
this.btnShow.setBounds(0,40,600,32);
// 給按鈕注冊監(jiān)聽
//給function函數(shù)中的show添加響應(yīng)事件
this.btnShow.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
btnShow_ActionPerformed(ae);
}
});
// 將組件加入到窗體中
add(this.scpDemo);
add(btnShow);
// 顯示窗體
this.setVisible(true);
}
// 點擊按鈕時的事件處理
public void btnShow_ActionPerformed(ActionEvent ae){
// 以下是連接數(shù)據(jù)源和顯示數(shù)據(jù)的具體處理方法,請注意下
try{
// 獲得連接
Class.forName("com.mysql.jdbc.Driver");//根據(jù)報錯信息修改
String url = "jdbc:mysql://localhost:3307/users?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false";//鏈接的mysql
String user = "root";
String passwd = "123456";
Connection conn = DriverManager.getConnection(url,user,passwd);//處理異常
System.out.println("Mysql連接成功" + conn.toString());//測試是否連接成功
// 建立查詢條件
String sql = "select * from userinfo";
PreparedStatement pstm = conn.prepareStatement(sql);
// 執(zhí)行查詢
ResultSet rs = pstm.executeQuery();
// 計算有多少條記錄
int count = 0;
while(rs.next()){
count++;
}
rs = pstm.executeQuery();
// 將查詢獲得的記錄數(shù)據(jù),轉(zhuǎn)換成適合生成JTable的數(shù)據(jù)形式
Object[][] info = new Object[count][6];
count = 0;
while(rs.next()){
info[count][0] = rs.getString(1);
info[count][1] = rs.getString(2);
info[count][2] = rs.getString(3);
info[count][3] = rs.getString(4);
info[count][4] = rs.getString(5);
info[count][5] = rs.getString(6);
count++;
}
// 定義表頭
String[] title = {"編號","用戶名","手機號","性別","住址","郵箱"};
// 創(chuàng)建JTable
this.tabDemo = new JTable(info,title);
tabDemo.setSelectionBackground(Color.pink);
// 顯示表頭
this.jth = this.tabDemo.getTableHeader();
jth.setBackground(Color.orange);
// 將JTable加入到帶滾動條的面板中
this.scpDemo.getViewport().add(tabDemo);
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
JOptionPane.showMessageDialog(null,"數(shù)據(jù)源錯誤","錯誤",JOptionPane.ERROR_MESSAGE);
}catch(SQLException sqle){
JOptionPane.showMessageDialog(null,"數(shù)據(jù)操作錯誤","錯誤",JOptionPane.ERROR_MESSAGE);
}
}
}
