JTable只显示Mysql中的一行

时间:2017-07-15 05:13:57

标签: java swing jtable

我是Java语言的新手。我想将Mysql数据库中的记录显示为JTable ..但我只有一行..我不知道我哪里出错了。任何帮助都将受到高度赞赏。

我的代码是:

package test;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.sql.*;
import net.proteanit.sql.DbUtils;

class Test {
    JFrame frame;
    Container pane;
    JTable table;
    Connection con;
    Statement sth;
    ResultSet rs;

    public void connect () {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/SMS", "root", "phplover");
        } catch (Exception e) {
            System.out.println("Conection failed. " + e);
        }
    }

    public void initGUI () {
        frame = new JFrame();
        frame.setVisible(true);
        frame.setBounds(100, 100, 500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        pane = frame.getContentPane();
    }

    public void fetchRecords () {
        try {
            sth = con.createStatement();
            rs = sth.executeQuery("SELECT * FROM `students`");

            while (rs.next()) {
                String name = rs.getString("name");
                String fname = rs.getString("fname");
                String age = rs.getString("age");

                String cols[] = {"Name", "Father's Name", "Age"};
                String rows[][] = {
                    {name, fname, age}
                };
                table = new JTable(rows, cols);
                pane.add(new JScrollPane(table));
            }

        } catch (Exception e) {
            System.out.println("An error occured. " + e);
        }
    }

    public static void main (String args[]) {
        Test obj = new Test();
        obj.connect();
        obj.initGUI();
        obj.fetchRecords();
    }

}

1 个答案:

答案 0 :(得分:0)

您的问题主要在于,当您遍历数据库时,每次都会创建一个全新的JTable。在下面的示例中,我不仅修复了您的问题,还修复了

一些指示:

  1. 请勿使用getContentPane(),创建JPanel并为其指定布局。对于你,我选择了BorderLayout,如果你愿意,你可以自己选择。
  2. 不要在JFrame上使用setBounds()。地狱,不要在任何Swing组件上使用它。 Heres some good reasons why.
  3. 使用JFrame.setDefaultLocationRelativeTo(null)将其放置在屏幕中央。我相信你正在使用setBounds()
  4. 在 框架初始化后使用JFrame.setVisible(true) 。否则,随着所有内容的添加,你会随处跳跃。
  5. 最后,代码:

    public class Test {
        JFrame frame;
        JPanel window;
        JTable table;
        JScrollPane scrollPane;
    
        Connection con;
        Statement sth;
        ResultSet rs;
    
        public void connect () {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/SMS", "root", "phplover");
            } catch (Exception e) {
                System.out.println("Conection failed. " + e);
            }
        }
    
        public void initGUI () {
            frame = new JFrame();
            frame.setSize(400, 400);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
    
            window.setLayout(new BorderLayout());
            frame.add(window);
    
            scrollPane = new JScrollPane(table);
    
            // USE THIS ONE IF YOU WANT YOUR SCROLL BARS TO ALWAYS BE VISIBLE!
            //scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    
            window.add(scrollPane, BorderLayout.CENTER);
    
            frame.setVisible(true);
        }
    
        public void fetchRecords () {
            try {
                sth = con.createStatement();
                rs = sth.executeQuery("SELECT * FROM `students`");
    
                String[] columns = {"Name", "Father's Name", "Age"};
    
                List<Object[]> sets = new ArrayList<Object[]>();
                while (rs.next()) {
                    String name = rs.getString("name");
                    String fname = rs.getString("fname");
                    String age = rs.getString("age");
    
                    sets.add(new String[]{name, fname, age});
                }
                table = new JTable(sets.toArray(new Object[sets.size()][]), columns);
            } catch (Exception e) {
                System.out.println("An error occured. " + e);
            }
        }
    
        public static void main (String args[]) {
            Test obj = new Test();
            obj.connect();
            obj.fetchRecords(); // Notice I swapped the order between this and initGUI.
            obj.initGUI();      // The program will break if you have it the other way around as the
                                // JTable will throw a NullPointerException.
        }
    }
    

    注意:这会在记录提取过程中初始化JTable。您可以随时编辑它,但通过再次调用fetchRecords(),它将通过数据库更新它。对于加载新数据非常有用,但它会删除您自己添加的所有数据,除非您先将这些更改推送到数据库。