繁体   English   中英

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组件上使用它。 这里有一些很好的理由。
  3. 使用JFrame.setDefaultLocationRelativeTo(null)将其放置在屏幕中央。 我相信这就是您使用setBounds()所做的事情。
  4. 框架初始化 ,使用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()编辑,但是通过再次调用fetchRecords() ,它将通过数据库进行更新。 这对于加载新数据非常有用,但是它将删除您自己添加的所有数据,除非您首先将这些更改推送到数据库中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM