JTable 仅显示 Mysql 中的一行

JTable shows only one row from Mysql

我是 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();
    }

}

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

一些提示:

  1. 不要使用 getContentPane(),创建一个 JPanel 并给它一个布局。对于你,我选择了BorderLayout,你可以根据自己的喜好选择。
  2. 不要在 JFrame 上使用 setBounds()。该死,永远不要在任何 Swing 组件上使用它。 Heres some good reasons why.
  3. 使用JFrame.setDefaultLocationRelativeTo(null)将其定位在屏幕中央。我相信这就是你对 setBounds().
  4. 所做的
  5. 使用JFrame.setVisible(true) 框架初始化之后。否则你会在添加所有内容时让它到处跳动。

最后,代码:

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(),它将通过数据库更新它。对于加载新数据非常有用,但它会删除您自己添加的所有数据,除非您先将这些更改推送到数据库。