从MySQL更新GUI中的JTable

时间:2017-04-18 15:50:46

标签: java mysql database user-interface jtable

我创建了一个连接到数据库的GUI,在JTable中显示的JFrame中显示数据库信息但是当使用添加数据按钮时,我收到的数据已被添加到MySQL,但表不更新?在此之后,下一步是更新/删除条目,并在表格中显示。

我对Java中的GUI比较陌生,只是想知道我是否缺少一个方法,因为我认为populateTable();函数应该从我的populateTable();方法自动执行此操作。

这是我到目前为止所写的一切

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
import net.proteanit.sql.DbUtils;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComboBox;
import javax.swing.JTextPane;

public class GUI3 extends JFrame {

    private static final long serialVersionUID = 1L;

    // DB Code
    DBHelper dbhelper = new DBHelper();
    Connection con = dbhelper.open();
    Statement st;
    ResultSet rs;

    DefaultTableModel model = new DefaultTableModel();

    private JPanel contentPane;
    private JTable table;
    private JTextField userText;
    private JTextField ageText;
    private JTextField surText;
    private JTextField genreText;
    private JTextField hairText;
    private JTextField genderText;
    private JTextField firstText;
    private GUI3 frame;
    private final Action action = new SwingAction();

    /**
     * Launch the application.
     */
    public void main() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    frame = new GUI3();
                    frame.setVisible(true);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });                 
    }

    private void getUsersDataFromDB() {
        try {
            st = con.createStatement();
            String searchQuery = "SELECT * FROM user";
            rs = st.executeQuery(searchQuery);              
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            JOptionPane.showMessageDialog(null, (ex.getMessage()));
        }
    }

    private void populateTable() {
        getUsersDataFromDB();
        table.setModel(DbUtils.resultSetToTableModel(rs));
        JTableHeader th = table.getTableHeader();
        TableColumnModel tcm = th.getColumnModel();
        tcm.getColumn(0).setHeaderValue("User id");
        tcm.getColumn(1).setHeaderValue("Genre");
        tcm.getColumn(2).setHeaderValue("Hair Length");
        tcm.getColumn(3).setHeaderValue("Name");
        tcm.getColumn(4).setHeaderValue("Surname");
        tcm.getColumn(5).setHeaderValue("Age");
        tcm.getColumn(6).setHeaderValue("Gender");
        th.repaint();
    }

    /**
     * Create the frame.
     */

    public GUI3() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 600, 426);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(17, 5, 548, 167);

        userText = new JTextField();
        userText.setBounds(17, 180, 70, 20);
        userText.setColumns(10);

        ageText = new JTextField();
        ageText.setBounds(415, 180, 75, 20);
        ageText.setColumns(10);

        surText = new JTextField();
        surText.setBounds(335, 180, 75, 20);
        surText.setColumns(10);

        genreText = new JTextField();
        genreText.setBounds(95, 180, 75, 20);
        genreText.setColumns(10);

        JButton addButton = new JButton("Add");
        addButton.setBounds(85, 225, 100, 25);
        addButton.addActionListener(new ActionListener()
        {
              @Override
                public void actionPerformed(ActionEvent e) {
                 String searchQuery = "INSERT INTO `user`(`user_id`, `genre_id`, `hair_length`, "+ "`user_fname`,`user_lname`,`user_age`,`user_gender`) " + "VALUES (?, ?, ?, ?, ?, ?, ?)";
                    try (PreparedStatement insert = con.prepareStatement(searchQuery)) {
                        insert.setString(1, userText.getText());
                        insert.setString(2, genreText.getText());
                        insert.setString(3, hairText.getText());
                        insert.setString(4, firstText.getText());
                        insert.setString(5, surText.getText());
                        insert.setString(6, ageText.getText());
                        insert.setString(7, genderText.getText());
                        JOptionPane.showMessageDialog(null, "Data Added To MySQL");
                    }catch(Exception ex){
                        ex.printStackTrace();
                    }
                    populateTable();
                }
            });



        // Update Button Functionality
        JButton updateButton = new JButton("Update");
        updateButton.setBounds(185, 225, 100, 25);
        updateButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            String searchQuery = "UPDATE user (user_id, genre_id, hair_length, " + "user_fname, user_lname, user_age, user_gender) " + "VALUES (?, ?, ?, ?, ?, ?, ?)";  

                try (PreparedStatement insert = con.prepareStatement(searchQuery)) 
                {
                    insert.setString(1, userText.getText());
                    insert.setString(2, genreText.getText());
                    insert.setString(3, hairText.getText());
                    insert.setString(4, firstText.getText());
                    insert.setString(5, surText.getText());
                    insert.setString(6, ageText.getText());
                    insert.setString(7, genderText.getText());
                    JOptionPane.showMessageDialog(null, "Database Updated");
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
                populateTable();
            }
        });


        // Delete Button Functionality
        JButton deleteButton = new JButton("Delete");
        deleteButton.setBounds(285, 225, 100, 25);
        deleteButton.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent e) 
            {
                 String searchQuery = "DELETE FROM USER WHERE (user_id, genre_id, hair_length, " + "user_fname, user_lname, user_age, user_gender) " + "VALUES (?, ?, ?, ?, ?, ?, ?)";  

                    try (PreparedStatement insert = con.prepareStatement(searchQuery)) {
                        insert.setString(1, userText.getText());
                        insert.setString(2, genreText.getText());
                        insert.setString(3, hairText.getText());
                        insert.setString(4, firstText.getText());
                        insert.setString(5, surText.getText());
                        insert.setString(6, ageText.getText());
                        insert.setString(7, genderText.getText());
                        JOptionPane.showMessageDialog(null, "Database Updated");
                    }catch(Exception ex){
                        ex.printStackTrace();
                    }
            }
        });

        hairText = new JTextField();
        hairText.setBounds(175, 180, 75, 20);
        hairText.setColumns(10);

        genderText = new JTextField();
        genderText.setBounds(495, 180, 70, 20);
        genderText.setColumns(10);

        firstText = new JTextField();
        firstText.setBounds(255, 180, 75, 20);
        firstText.setColumns(10);

        table = new JTable();
        populateTable();


        scrollPane.setViewportView(table);
        contentPane.setLayout(null);
        contentPane.add(firstText);
        contentPane.add(scrollPane);
        contentPane.add(userText);
        contentPane.add(genreText);
        contentPane.add(hairText);
        contentPane.add(surText);
        contentPane.add(ageText);
        contentPane.add(genderText);
        contentPane.add(addButton);
        contentPane.add(updateButton);
        contentPane.add(deleteButton);

        JComboBox comboBox = new JComboBox();
        comboBox.setBounds(35, 285, 75, 20);
        contentPane.add(comboBox);

        JComboBox comboBox_1 = new JComboBox();
        comboBox_1.setBounds(35, 310, 75, 20);
        contentPane.add(comboBox_1);

        JComboBox comboBox_2 = new JComboBox();
        comboBox_2.setBounds(35, 335, 75, 20);
        contentPane.add(comboBox_2);

        JTextPane textPane = new JTextPane();
        textPane.setBounds(285, 285, 270, 75);
        contentPane.add(textPane);

    }

}

1 个答案:

答案 0 :(得分:0)

您需要在更新,删除或添加后刷新您的表格,首先清除您的表格然后在显示消息对话框之后或之前立即填写表格成功添加/更新/删除或等等

JOptionPane.showMessageDialog(null, "Database Updated");
model.setRowCount(0);//clear table data
populateTable();//method you use to populate your table`