电脑爱好者之家

当前位置: 主页 > JAVA编程文档 >

Java程序动态添加数据到JTable

时间:2014-04-03 02:05来源:未知 作者:机器AI 点击:
下面的代码是关于如何动态的向一个JTable控件中添加数据的方法。代码比较长,基本是完整的,可以直接使用,主要是拿出来给大家作参考,自己也留一个备份,以后可以用。

下面的代码是关于如何动态的向一个JTable控件中添加数据的方法。代码比较长,基本是完整的,可以直接使用,主要是拿出来给大家作参考,自己也留一个备份,以后可以用。

import java.awt.Toolkit;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.Dimension;

public class JTableAppClass {
    boolean packFrame = false;

  
    public JTableAppClass() {
        JTableAppFrame frame = new JTableAppFrame();
        // Validate frames that have preset sizes
        // Pack frames that have useful preferred size info, e.g. from their layout
        if (packFrame) {
            frame.pack();
        } else {
            frame.validate();
        }

        // Center the window
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frameSize = frame.getSize();
        if (frameSize.height > screenSize.height) {
            frameSize.height = screenSize.height;
        }
        if (frameSize.width > screenSize.width) {
            frameSize.width = screenSize.width;
        }
        frame.setLocation((screenSize.width - frameSize.width) / 2,
                          (screenSize.height - frameSize.height) / 2);
        frame.setVisible(true);
    }

  
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.
                                             getSystemLookAndFeelClassName());
                } catch (Exception exception) {
                    exception.printStackTrace();
                }

                new JTableAppClass();
            }
        });
    }
}

操作类:JTableAppFrame.java

package jtabletest;

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import java.awt.Rectangle;
import javax.swing.JScrollPane;
import java.util.Vector;
import java.sql.*;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;

public class JTableAppFrame extends JFrame {
    JPanel contentPane;
    Vector CellsVector = new Vector();
    Vector TitleVector = new Vector();
    JScrollPane scp = new JScrollPane();
    JTable tab = null;
    DBCon dbcon = new DBCon();
    JLabel lbl_name = new JLabel();
    JLabel lbl_age = new JLabel();
    JLabel lbl_address = new JLabel();
    JTextField txt_name = new JTextField();
    JTextField txt_age = new JTextField();
    JTextField txt_address = new JTextField();
    JButton btn_add = new JButton();
    JButton btn_del = new JButton();
    JButton btn_update = new JButton();
    JButton btn_reset = new JButton();
    public JTableAppFrame() {
        try {
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            jbInit();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

  
    private void jbInit() throws Exception {
        contentPane = (JPanel) getContentPane();
        contentPane.setLayout(null);
        this.setResizable(false);
        setSize(new Dimension(400, 340));
        setTitle("JTable");
        scp.setBounds(new Rectangle(46, 32, 297, 157));
        lbl_name.setFont(new java.awt.Font("宋体", Font.BOLD, 12));
        lbl_name.setText("姓名:");
        lbl_name.setBounds(new Rectangle(46, 205, 42, 15));
        lbl_age.setFont(new java.awt.Font("宋体", Font.BOLD, 12));
        lbl_age.setText("年龄:");
        lbl_age.setBounds(new Rectangle(200, 205, 42, 15));
        lbl_address.setFont(new java.awt.Font("宋体", Font.BOLD, 12));
        lbl_address.setText("地址:");
        lbl_address.setBounds(new Rectangle(46, 232, 42, 15));
        txt_name.setFont(new java.awt.Font("宋体", Font.BOLD, 12));
        txt_name.setBounds(new Rectangle(98, 205, 72, 21));
        txt_age.setFont(new java.awt.Font("宋体", Font.BOLD, 12));
        txt_age.setBounds(new Rectangle(250, 205, 72, 21));
        txt_address.setFont(new java.awt.Font("宋体", Font.BOLD, 12));
        txt_address.setBounds(new Rectangle(98, 232, 72, 21));
        btn_add.setBounds(new Rectangle(46, 271, 83, 25));
        btn_add.setFont(new java.awt.Font("宋体", Font.BOLD, 12));
        btn_add.setText("添 加");
        btn_add.addActionListener(new JTableAppFrame_btn_add_actionAdapter(this));
        btn_del.setBounds(new Rectangle(155, 271, 83, 25));
        btn_del.setFont(new java.awt.Font("宋体", Font.BOLD, 12));
        btn_del.setText("删 除");
        btn_del.addActionListener(new JTableAppFrame_btn_del_actionAdapter(this));
        btn_update.setBounds(new Rectangle(260, 271, 83, 25));
        btn_update.setFont(new java.awt.Font("宋体", Font.BOLD, 12));
        btn_update.setText("修 改");
        btn_update.addActionListener(new
                                     JTableAppFrame_btn_update_actionAdapter(this));
        btn_reset.setBounds(new Rectangle(258, 232, 83, 25));
        btn_reset.setFont(new java.awt.Font("宋体", Font.BOLD, 12));
        btn_reset.setText("重 置");
        btn_reset.addActionListener(new JTableAppFrame_btn_reset_actionAdapter(this));
        contentPane.add(scp);
        contentPane.add(lbl_name);
        contentPane.add(lbl_age);
        contentPane.add(lbl_address);
        contentPane.add(txt_name);
        contentPane.add(txt_age);
        contentPane.add(txt_address);
        contentPane.add(btn_del);
        contentPane.add(btn_update);
        contentPane.add(btn_add);
        contentPane.add(btn_reset);
        dbcon.connectDB();
        this.showTable();
        tab = new JTable(CellsVector, TitleVector);
        scp.getViewport().add(tab);
    }

  
    public void showTable() {
        this.TitleVector.add("姓名");
        this.TitleVector.add("年龄");
        this.TitleVector.add("地址");
        dbcon.select();
        ArrayList list = dbcon.select();
        for (int i = 0; i < list.size(); i++) {
            Student stu = (Student) list.get(i);
            Vector v = new Vector();
            v.add(stu.getName());
            v.add(stu.getAge());
            v.add(stu.getAddress());
            CellsVector.add(v);
        }
    }


  
    String name;
    String age;
    String address;
    public int checkInformation() {
        name = this.txt_name.getText();
        age = this.txt_age.getText();
        address = this.txt_address.getText();
        if (name.equals("")) {
            JOptionPane.showMessageDialog(this, "您好!请输入姓名!", "提示", 1);
            this.txt_name.grabFocus();
            return 0;
        }
        if (age.equals("")) {
            JOptionPane.showMessageDialog(this, "您好!请输入年龄!", "提示", 1);
            this.txt_age.grabFocus();
            return 0;
        }
        char[] ans = age.toCharArray();
        for (int i = 0; i < ans.length; i++) {
            if (!Character.isDigit(ans[i])) {
                JOptionPane.showMessageDialog(this, "您好!年龄输入错误!", "提示", 1);
                this.txt_age.setText("");
                this.txt_age.grabFocus();
                return 0;
            }
        }
        if (age.length() > 3) {
            JOptionPane.showMessageDialog(this, "您好!年龄最高只能为 100 岁!", "提示", 1);
            this.txt_age.setText("");
            this.txt_age.grabFocus();
            return 0;
        }
        if (address.equals("")) {
            JOptionPane.showMessageDialog(this, "您好!请输入地址!", "提示", 1);
            this.txt_address.grabFocus();
            return 0;
        }
        ages = Integer.valueOf(age);
        return 1;
    }

  
    int ages;
    public void btn_add_actionPerformed(ActionEvent e) {
        if (this.checkInformation() == 0) {
            return;
        }
        dbcon.insert(name, ages, address);
        this.CellsVector.clear();
        this.showTable();
        this.tab.updateUI();
        this.btn_reset_actionPerformed(e);
    }

  
    ResultSet rs;
    public void btn_del_actionPerformed(ActionEvent e) {
        String name = this.txt_name.getText();
        this.txt_age.setEditable(false);
        this.txt_address.setEditable(false);

        if (name.equals("")) {
            JOptionPane.showMessageDialog(this, "您好!请输入姓名!", "提示", 1);
            this.txt_name.grabFocus();
            return;
        }
        try {
            String sql = "select * from Student where name=?";
            PreparedStatement ps = DBCon.con.prepareStatement(sql);
            ps.setString(1, name);
            rs = ps.executeQuery();
            if (rs.next()) {
                ps.close();
                dbcon.delete(name);
                this.CellsVector.clear();
                this.showTable();
                this.tab.updateUI();
                this.btn_reset_actionPerformed(e);
            } else {
                JOptionPane.showMessageDialog(this, "您好!该学员不存在!", "提示", 1);
                this.btn_reset_actionPerformed(e);
                return;
            }
        } catch (SQLException ex) {
            System.out.println("核对学员信息发生异常" + ex.getMessage());
        }
    }

  
    public void btn_update_actionPerformed(ActionEvent e) {
        if (this.checkInformation() == 0) {
            return;
        }
        try {
            String sql = "select * from Student where name=?";
            PreparedStatement ps = DBCon.con.prepareStatement(sql);
            ps.setString(1, name);
            rs = ps.executeQuery();
            if (rs.next()) {
                ps.close();
                dbcon.update(name, ages, address);
                this.CellsVector.clear();
                this.showTable();
                this.tab.updateUI();
                this.btn_reset_actionPerformed(e);
            } else {
                JOptionPane.showMessageDialog(this, "您好!该学员不存在!", "提示", 1);
                this.btn_reset_actionPerformed(e);
                return;
            }
        } catch (SQLException ex) {
            System.out.println("核对学员信息发生异常" + ex.getMessage());
        }

    }

  
    public void btn_reset_actionPerformed(ActionEvent e) {
        this.txt_name.setText("");
        this.txt_age.setText("");
        this.txt_address.setText("");
        this.txt_age.setEditable(true);
        this.txt_address.setEditable(true);
    }
}


class JTableAppFrame_btn_del_actionAdapter implements ActionListener {
    private JTableAppFrame adaptee;
    JTableAppFrame_btn_del_actionAdapter(JTableAppFrame adaptee) {
        this.adaptee = adaptee;
    }

    public void actionPerformed(ActionEvent e) {
        adaptee.btn_del_actionPerformed(e);
    }
}


class JTableAppFrame_btn_update_actionAdapter implements ActionListener {
    private JTableAppFrame adaptee;
    JTableAppFrame_btn_update_actionAdapter(JTableAppFrame adaptee) {
        this.adaptee = adaptee;
    }

    public void actionPerformed(ActionEvent e) {
        adaptee.btn_update_actionPerformed(e);
    }
}


class JTableAppFrame_btn_reset_actionAdapter implements ActionListener {
    private JTableAppFrame adaptee;
    JTableAppFrame_btn_reset_actionAdapter(JTableAppFrame adaptee) {
        this.adaptee = adaptee;
    }

    public void actionPerformed(ActionEvent e) {
        adaptee.btn_reset_actionPerformed(e);
    }
}


class JTableAppFrame_btn_add_actionAdapter implements ActionListener {
    private JTableAppFrame adaptee;
    JTableAppFrame_btn_add_actionAdapter(JTableAppFrame adaptee) {
        this.adaptee = adaptee;
    }

    public void actionPerformed(ActionEvent e) {
        adaptee.btn_add_actionPerformed(e);
    }
}

连接数据库类:DBCon.java

package jtabletest;

import java.sql.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;

public class DBCon {
    static Connection con;
    private final String DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
    private final String URL = "jdbc:odbc:test";
    ResultSet rs = null;
    Statement st = null;
    public DBCon() {
    }

  
    public void connectDB() {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException ex) {
            System.out.println(ex.getMessage());
        }
        if (con == null) {
            try {
                con = DriverManager.getConnection(URL);
            } catch (SQLException ex) {
                System.out.println("创建连接发生异常:" + ex.getMessage());
                System.exit(0);
            }
        }
    }

  
    public ArrayList select() {
        ArrayList list = new ArrayList();
        String sql = "select * from Student";
        try {
            st = con.createStatement();
            rs = st.executeQuery(sql);
            while (rs.next()) {
                Student stu = new Student();
                stu.setName(rs.getString(2));
                stu.setAge(rs.getInt(3));
                stu.setAddress(rs.getString(4));
                list.add(stu);
            }
        } catch (SQLException ex) {
            System.out.println("查询数据发生异常:" + ex.getMessage());
        } finally {
            try {
                rs.close();
            } catch (SQLException ex1) {
                System.out.println("查询数据关闭语句异常:" + ex1.getMessage());
            }
        }
        return list;
    }

  
    public void insert(String name, int age, String address) {
        String sql = "insert into Student values(?,?,?)";
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(sql);
            ps.setString(1, name);
            ps.setInt(2, age);
            ps.setString(3, address);
            if (ps.executeUpdate() != 0) {
                JOptionPane.showMessageDialog(null, "恭喜!插入数据成功!", "消息", 1);
            }
        } catch (SQLException ex) {
            System.out.println("插入数据发生异常:" + ex.getMessage());
        } finally {
            try {
                ps.close();
            } catch (SQLException ex1) {
                System.out.println("插入数据关闭语句异常:" + ex1.getMessage());
            }
        }
    }

  
    public void update(String name, int age, String address) {
        String sql = "update Student set age = ?,address = ? where name =?";
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(sql);
            ps.setInt(1, age);
            ps.setString(2, address);
            ps.setString(3, name);
            if (ps.executeUpdate() != 0) {
                JOptionPane.showMessageDialog(null, "恭喜!更新数据成功!", "消息", 1);
            }
        } catch (SQLException ex) {
            System.out.println("修改数据发生异常!");
        } finally {
            try {
                ps.close();
            } catch (SQLException ex1) {
                System.out.println("修改数据关闭语句异常:" + ex1.getMessage());
            }
        }
    }

  
    public void delete(String name) {
        String sql = "delete from Student where name =?";
        PreparedStatement ps = null;
        int delNumber;
        try {
            ps = con.prepareStatement(sql);
            ps.setString(1, name);
            delNumber = ps.executeUpdate();
            if (delNumber != 0) {
                JOptionPane.showMessageDialog(null, "恭喜!删除数据成功!", "消息", 1);
            }
        } catch (SQLException ex) {
            System.out.println("删除数据发生异常:" + ex.getMessage());
        } finally {
            try {
                ps.close();
            } catch (SQLException ex1) {
                System.out.println("删除数据关闭语句异常:" + ex1.getMessage());
            }
        }
    }

  
    public void destoryConnection() {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException ex) {
                System.out.println("释放连接异常:" + ex.getMessage());
            }
        }
    }
}

JavaBean 类:Student.java

package jtabletest;

public class Student {
    private String name;
    private int age;
    private String address;
    public Student() {
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getAddress() {
        return address;
    }
}

(责任编辑:机器AI)
织梦二维码生成器
顶一下
(1)
50%
踩一下
(1)
50%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片