Java jtable中的sql数据表

Java jtable中的sql数据表,java,swing,netbeans,Java,Swing,Netbeans,我是java netbeans编程的新手,因此我尝试在jFrame表中显示数据表,但它不起作用,因此下面的代码: package presentation; import DAO.signalisation_freelancerDAO; import technique.myconnexion; import javax.swing.*; import java.sql.*; import DAO.FreelancerDAO; import EN

我是java netbeans编程的新手,因此我尝试在jFrame表中显示数据表,但它不起作用,因此下面的代码:

 package presentation;
    import DAO.signalisation_freelancerDAO;
    import technique.myconnexion;
    import javax.swing.*;
    import java.sql.*;
    import DAO.FreelancerDAO;
    import ENTITE.Freelancer;
    import ENTITE.signalisation_freelancer;
    import java.util.*;
    import javax.swing.DefaultListModel;
    import javax.swing.JOptionPane;
    import net.proteanit.sql.DbUtils;



    public class ListFreelancerSingalise1 extends javax.swing.JFrame {

    Connection url=null;
    ResultSet rs=null;
    PreparedStatment pst=null;


    public ListFreelancerSingalise1() {
    initComponents();
    url=myconnexion.myConnection;
    Update_table();
    }
    private void Update_table()
    {
    try{
    String sql="select * from signalisation_freelancer";
    pst=(PreparedStatment) url.prepareStatement(sql);
    rs=pst.executeQuery();
    jTable1.setModel(DbUtils.resultSetToTableModel(rs));
    }

    catch(Exception e ){
    JOptionPane.showMessageDialog(null,e);
    }




    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

    jRadioButtonMenuItem1 = new javax.swing.JRadioButtonMenuItem();
    jLabel1 = new javax.swing.JLabel();
    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();

    jRadioButtonMenuItem1.setSelected(true);
    jRadioButtonMenuItem1.setText("jRadioButtonMenuItem1");

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("Liste des freelancer signalisé");

    jButton1.setText("Activer");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    }
    });

    jButton2.setText("Supprimer");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    }
    });

    jButton3.setText("recherche");

    javax.swing.GroupLayout jPanel1Layout = new               
    javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
                  jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(50, 50, 50)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addContainerGap(45, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jButton3)
            .addGap(18, 18, 18)
            .addComponent(jButton1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jButton2)
            .addGap(8, 8, 8))
    );

    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null}
        },
        new String [] {
            "Title 1", "Title 2", "Title 3", "Title 4"
        }
    ));
    jScrollPane1.setViewportView(jTable1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(157, 157, 157)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(51, 51, 51)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(193, 193, 193)
                    .addComponent(jLabel1)))
            .addContainerGap(90, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(20, 20, 20)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );

    pack();
}// </editor-fold>                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

}                                        

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
}                                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(ListFreelancerSingalise1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(ListFreelancerSingalise1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(ListFreelancerSingalise1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(ListFreelancerSingalise1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new ListFreelancerSingalise1().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration                   

这里是我在intrface jFrame中编译时的结果,jtable为空,因此任何关于此的帮助:(

< p>假设您从数据库中获取数据,我认为它应该出现在您的Swing表中。考虑添加一些PrtLn语句来检查您是否接收到您期望的数据库中的数据。对于按钮的更新和删除,您需要向JButt(1×2)Accon执行的方法添加代码。例如:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    updateTable();
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    jTable1.setModel(DbUtils.getEmptyTableModel());
}
为了使您的应用程序在没有数据库的情况下为我工作,我更改了
updateTable
方法(请注意其他方法):

如果包含对使用的外部库的引用,则可以节省时间。我在查找您使用的
DbUtils
类时遇到了一些困难。经过一些搜索后,我在上找到了它的一个版本。后来我在上也看到了它

这是TechnoJeeves的版本,我对其进行了一些修改和扩展(添加了一些测试方法):

package com.stackoverflow.q28649773;
导入java.sql.ResultSet;
导入java.sql.ResultSetMetaData;
导入java.sql.SQLException;
导入java.util.ArrayList;
导入java.util.List;
导入java.util.Vector;
导入javax.swing.table.DefaultTableModel;
导入javax.swing.table.TableModel;
/**
*源于http://technojeeves.com/index.php/9-freebies/22-resultset-to-tablemodel.
*/
公共类DbUtils{
/**
*将数据库结果集转换为Swing表模型。
*
*@param resultSet输入数据库结果集。
*@返回已构建的回转台模型。
*/
公共静态表模型ResultSetTableModel(最终结果集ResultSet){
TableModel结果=null;
试一试{
final ResultSetMetaData metaData=resultSet.getMetaData();
final int numberOfColumns=metaData.getColumnCount();
//获取列名。
最终列表columnNames=新ArrayList();
对于(int columnIndex=1;columnIndex
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    updateTable();
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    jTable1.setModel(DbUtils.getEmptyTableModel());
}
private void updateTable() {
    try {
        if (url != null) {
            final String sql = "select * from signalisation_freelancer";
            pst = url.prepareStatement(sql);
            rs = pst.executeQuery();
            jTable1.setModel(DbUtils.resultSetToTableModel(rs));
        } else
            jTable1.setModel(DbUtils.getTestTableModel());
    } catch (final SQLException e) {
        JOptionPane.showMessageDialog(null, e);
    }
}
package com.stackoverflow.q28649773;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

/**
 * Originally from http://technojeeves.com/index.php/9-freebies/22-resultset-to-tablemodel.
 */
public class DbUtils {
    /**
     * Convert a database result set to a Swing table model.
     *
     * @param resultSet the input database result set.
     * @return the Swing table model that has been constructed.
     */
    public static TableModel resultSetToTableModel(final ResultSet resultSet) {
        TableModel result = null;

        try {
            final ResultSetMetaData metaData = resultSet.getMetaData();
            final int numberOfColumns = metaData.getColumnCount();

            // Get the column names.
            final List<String> columnNames = new ArrayList<>();
            for (int columnIndex = 1; columnIndex <= numberOfColumns; columnIndex++)
                columnNames.add(metaData.getColumnLabel(columnIndex));

            // Get all rows with data.
            final List<List<Object>> data = new ArrayList<>();
            while (resultSet.next()) {
                final List<Object> newRow = new ArrayList<>();
                for (int columnIndex = 1; columnIndex <= numberOfColumns; columnIndex++) {
                    System.out.println(resultSet.getObject(columnIndex));
                    newRow.add(resultSet.getObject(columnIndex));
                }

                data.add(newRow);
            }

            result = new DefaultTableModel(new Vector<>(data), new Vector<>(columnNames));
        } catch (final SQLException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static TableModel getTestTableModel() {
        final String[] columnNames = {"A", "B", "C"};
        final Object[][] data = {{"1", "2", "3"}, {"i", "ii", "iii"}};
        return new DefaultTableModel(data, columnNames);
    }

    public static TableModel getEmptyTableModel() {
        final String[] columnNames = {"A", "B", "C"};
        final Object[][] data = {};
        return new DefaultTableModel(data, columnNames);
    }
}