Swing中使用JTable动态获取数据库中的数据并显示

Posted --清风徐来--

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swing中使用JTable动态获取数据库中的数据并显示相关的知识,希望对你有一定的参考价值。

笔者注:本文供新手学习使用,若有一定基础,可以直接看3!

 

1.创建数据库:

/*
Navicat mysql Data Transfer

Source Server         : aa
Source Server Version : 50519
Source Host           : localhost:3306
Source Database       : test

Target Server Type    : MYSQL
Target Server Version : 50519
File Encoding         : 65001

Date: 2017-05-05 20:59:36
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(12) DEFAULT NULL,
  `password` varchar(12) DEFAULT NULL,
  `sex` char(4) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(12) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (\'1\', \'李雷\', \'123\', \'\', \'23\', \'湖北十堰\');
INSERT INTO `user` VALUES (\'2\', \'韩梅梅\', \'111\', \'\', \'23\', \'湖北十堰\');
INSERT INTO `user` VALUES (\'3\', \'光头强\', \'123\', \'\', \'22\', \'森林\');
INSERT INTO `user` VALUES (\'4\', \'熊大\', \'111\', \'\', \'22\', \'森林\');
INSERT INTO `user` VALUES (\'5\', \'喜羊羊\', \'111\', \'\', \'16\', \'青青草原羊村\');
INSERT INTO `user` VALUES (\'6\', \'美羊羊\', \'123\', \'\', \'16\', \'青青草原羊村\');
INSERT INTO `user` VALUES (\'7\', \'灰太狼\', \'111\', \'\', \'18\', \'青青草原狼堡\');
INSERT INTO `user` VALUES (\'8\', \'红太郎\', \'123\', \'\', \'18\', \'青青草原狼堡\');

2.创建项目:

2.1按照以下格式创建项目

 

2.2导入mysql链接数据库jar包(jar包下载地址:http://download.csdn.net/detail/yangs_1235/5049404)

2.2.1在项目内新建一个文件夹lib

 

2.2.2将jar包赋值到lib目录下,并添加到项目中(反键,如图所示即可)

 

 

注:1.DbUtils类主要写JDBC链接数据库代码,代码如下:

package com.zjl.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DbUtils {
    
    private  static  final String URL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";              
    private  static  final String USER="root";
    private  static  final String PASSWORD="scme";//此处为数据库密码,更改为自己数据库的密码
    
    static{
          try {  
              Class.forName("com.mysql.jdbc.Driver");                
           } catch (ClassNotFoundException e) {
               e.printStackTrace();
           }
    }
        
    public static Connection getConnection() throws SQLException{
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }
    
    //关闭方法
    public  static void close(ResultSet rs, Statement stat, Connection conn) throws SQLException{
        if(rs!=null){
            rs.close();
        }if(stat!=null){
            stat.close();
        }if(conn!=null){
            conn.close();
        }
    }    
    
}    

2.User类主要是储存数据的实体类,代码如下:

package com.zjl.modle;

public class User {
    private int id,age;
    private String name,password,sex,address;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    

}

3.UserDao主要是进行数据操作的类,代码如下:

package com.zjl.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.zjl.db.DbUtils;
import com.zjl.modle.User;

public class UserDao {
    private Connection conn=null;
    private PreparedStatement ps=null;
    private ResultSet rs=null;
    
    //查询所有用户
    public List<User> queryAllUser(){
        String sql="select * from user";
        List<User> list=new ArrayList<User>();
        try {
             conn=DbUtils.getConnection();
             ps=conn.prepareStatement(sql);
             rs=ps.executeQuery();
             System.out.println(ps.toString());
             while(rs.next()){
                 User user=new User();
                 user.setId(rs.getInt(1));
                 user.setName(rs.getString(2));
                 user.setPassword(rs.getString(3));
                 user.setSex(rs.getString(4));
                 user.setAge(rs.getInt(5));
                 user.setAddress(rs.getString(6));
                
                 
                 list.add(user);
             }
             
             
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
    
}

4.Main类是显示数据的窗体类,代码如下:

package com.zjl.view;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.util.List;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;

import com.zjl.dao.UserDao;
import com.zjl.modle.User;

public class Main extends JFrame {

    private JPanel contentPane;
    private JTable table;
    private String head[]=null;
    private Object [][]data=null;
    private UserDao user=new UserDao();
    

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Main frame = new Main();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Main() {
        setResizable(false);
        
        setTitle("\\u673A\\u7968\\u9884\\u8BA2\\u7CFB\\u7EDF");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 700, 300);
        Dimension   us=this.getSize();
        Dimension them=Toolkit.getDefaultToolkit().getScreenSize();
              
              int   x=(them.width-us.width)/2;  
              int   y=(them.height-us.height)/2;   
              
              this.setLocation(x, y);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(0,0,700,250);
        
        table = new JTable();
         
        table.setBorder(new LineBorder(new Color(0, 0, 0)));
        head=new String[] {
            "id", "姓名", "密码", "性别", "年龄", "住址", "\\u7968\\u4EF7",
        };
        
        DefaultTableModel tableModel=new DefaultTableModel(queryData(),head){
            public boolean isCellEditable(int row, int column)
            {
                return false;
            }
        };
        table.setModel(tableModel);

        scrollPane.setViewportView(table);
        GroupLayout gl_contentPane = new GroupLayout(contentPane);
        gl_contentPane.setHorizontalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 684, Short.MAX_VALUE)
        );
        gl_contentPane.setVerticalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 195, GroupLayout.PREFERRED_SIZE)
                    .addGap(66))
        );
        contentPane.setLayout(gl_contentPane);
        

    }
    
    //生成表格数据
    /**
     * @return
     */
    public Object[][] queryData(){
        List<User> list=user.queryAllUser();
        data=new Object[list.size()][head.length];

        for(int i=0;i<list.size();i++){
            for(int j=0;j<head.length;j++){
                data[i][0]=list.get(i).getId();
                data[i][1]=list.get(i).getName();
                data[i][2]=list.get(i).getPassword();
                data[i][3]=list.get(i).getSex();
                data[i][4]=list.get(i).getAge();
                data[i][5]=list.get(i).getAddress();
            }
        }
        return data;
    }

}

 

3.重点代码回顾:

3.1效果展示:

 

 3.2定义一个获取数据的方法

//生成表格数据
    /**
     * @return
     */
    public Object[][] queryData(){
        List<User> list=user.queryAllUser();
        data=new Object[list.size()][head.length];

        for(int i=0;i<list.size();i++){
            for(int j=0;j<head.length;j++){
                data[i][0]=list.get(i).getId();
                data[i][1]=list.get(i).getName();
                data[i][2]=list.get(i).getPassword();
                data[i][3]=list.get(i).getSex();
                data[i][4]=list.get(i).getAge();
                data[i][5]=list.get(i).getAddress();
            }
        }
        return data;
    }

3.3在窗体代码中使用DefaultTableModle绑定数据

String head[]=new String[] {"id", "姓名", "密码", "性别", "年龄", "住址"};
DefaultTableModel tableModel=new DefaultTableModel(queryData(),head);
table.setModel(tableModel);//JTable对象设置DefaultTableModle

 

作为一个带大一自习的学长,我为他们写下了这篇文章,也将这篇文章送给所有学习Swing的朋友们!

以上是关于Swing中使用JTable动态获取数据库中的数据并显示的主要内容,如果未能解决你的问题,请参考以下文章

Swing JTable动态增删行 列操作介绍(详细)

我用JAVA的swing创建了一个窗口程序,拖了一个jTable控件在窗体上,怎样把数据库中的内容显示在Table上?

Swing-JTable检测单元格数据变更事件

在java swing Jtable中设置隐藏字段值

如何完全擦除 Java Swing JTable 列及其数据?

Swing jtable 怎么合并单元格 合并行 合并列