如何在jTable上显示结果?

时间:2017-05-25 15:01:59

标签: java sql swing jtable resultset

我想知道如何将结果显示在jTable或txtfields上?

(stateful = False)

1 个答案:

答案 0 :(得分:0)

在此示例中,我试图向您展示如何填充JTable 来自数据库(带连接示例)..

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class JTableTest extends JFrame{

    private DefaultTableModel model;
    private JTable table;
    private final String[] colname;

    public JTableTest() {

        colname = new String[] { "NAME ", "EMAIL  " };  //table headers
        model = new DefaultTableModel(colname, 0);      //table model
        populateMyModel(model); //the following populating method
        table = new JTable(model);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.setFont(new Font("Monospaced", Font.PLAIN, 13));
        table.setBackground(new Color(245, 245, 245));
        table.setRowHeight(25);
        table.setMinimumSize(new Dimension(60, 20));

    }

    public void populateMyModel(DefaultTableModel model) {
        final String host = "com.mysql.jdbc.Driver";
        final String url = "localhost://database_name/table_name";
        final String user = "user_name";
        final String psw = "password";
        final Connection conn;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        String Name = "";
        String mail = "";

        try {
            Class.forName(host);
            conn = DriverManager.getConnection(url, user, psw);
            String SQL = "BLAH BLAH";
            preparedStatement = conn.prepareStatement(SQL);
            resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {

                Name = resultSet.getString("NAME");
                mail = resultSet.getString("EMAIL");

            }

            // here we populating the table model from database.
            this.model.addRow(new Object[] {Name, mail}); 

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

我尽可能多地表现出来,希望这对你有帮助。