首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用sql数据填充jtable

使用sql数据填充jtable
EN

Stack Overflow用户
提问于 2019-02-20 04:52:01
回答 1查看 0关注 0票数 0

我正在尝试使用mysql上的数据库中的数据填充jTable,并且没有任何事情发生。我知道有很多教程可以解决这个问题,但我做的都没有用。有人能帮我吗 ?

这是我的完整代码。(不要介意jComboBox下面的按钮我要删除它们)。关键是,当我在我的组合框中切换选择时,我应该在我的jTable中输入选择导入的所有sql数据。当我改变我的选择时,jTable会立即改变。

代码语言:javascript
复制
    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javafxapplication4;


import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.TableModel;
import java.sql.DbUtils;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Lord Jolson
 */
public class TableCon extends javax.swing.JFrame 
{

    //Méthode 1 : Remplir la combobox n°1 qui permettra de swap entre les éléments de la JTable

    //Ici une méthode est créer afin de feed une combobox des éléments ID et nom de la table t_serie de la base de donnée
    public TableCon() 
    {
        initComponents();
        listeSerie.addItem("Série");
        listeSerie.addItem("Casting");
        listeSerie.addItem("Épisode");
        listeSerie.addItem("Saison");
        listeSerie.addItem("Genre");
        listeSerie.addItem("Production");
        listeSerie.addItem("Scénariste");
        listeSerie.addItem("Pays d'Origine");
    }

    class ItemChangeListener implements ItemListener
    {        
        @Override
        @SuppressWarnings("empty-statement")
        public void itemStateChanged(ItemEvent event) 
        {              
            Connection conn = null;
            Statement stm = null;
            ResultSet res = null;  
            PreparedStatement statement = null;
            try
            {
                if (event.getStateChange() == ItemEvent.SELECTED) 
                {        
                    Object item = event.getItem();
                    if(item == "Série")
                    {
                        try
                        {
                            System.out.println("Connecting to database");
                            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/module104MaximeJoly","root","root");
                            System.out.println("Connected to database");
                            stm = conn.createStatement();
                            ResultSet rs = stm.executeQuery("select * from t_serie");
                            //TableModel.setModel(DbUtils.resultSetModel(rs));     

                            String n = "",e = "";      

                            DefaultTableModel model;
                            model = new DefaultTableModel(); 
                            TableModel = new  JTable(model);

                            model.addColumn("id Série");
                            model.addColumn("Nom de la série");

                            while(rs.next())  
                            {
                                n = rs.getString("id_serie");    
                                e= rs.getString("nom");   
                                model.addRow(new Object[]{n,e});
                            }
                        }
                        catch(Exception e)
                        {

                        }
                        finally
                        {
                            try
                            {                               
                                res.close();
                                stm.close();
                                conn.close();
                            }
                            catch(Exception e)
                            {

                            }
                        }
                    }
                }
            }                   
            catch (Exception ex) 
            {       
                Logger.getLogger(TableCon.class.getName()).log(Level.SEVERE, null, ex);
            } 

        }
    }






    //Remplissage de la jtable



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

        boutonAdd = new javax.swing.JButton();
        boutonUpdate = new javax.swing.JButton();
        BoutonDelete = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        TableModel = new javax.swing.JTable();
        listeSerie = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        boutonExit = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        boutonSerie = new javax.swing.JButton();
        boutonCasting = new javax.swing.JButton();
        boutonEpisode = new javax.swing.JButton();
        boutonSaison = new javax.swing.JButton();
        boutonGenre = new javax.swing.JButton();
        boutonProduction = new javax.swing.JButton();
        boutonScenariste = new javax.swing.JButton();
        boutonPays = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        boutonAdd.setText("Ajouter");
        boutonAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boutonAddActionPerformed(evt);
            }
        });

        boutonUpdate.setText("Update");

        BoutonDelete.setText("Supprimer");

        TableModel.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(TableModel);

        listeSerie.setEditable(true);
        listeSerie.setToolTipText("");
        listeSerie.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listeSerieActionPerformed(evt);
            }
        });

        jLabel1.setText("Choix de la table de la base de donnée");

        boutonExit.setText("EXIT");
        boutonExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boutonExitActionPerformed(evt);
            }
        });

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        boutonSerie.setText("Série");
        boutonSerie.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boutonSerieActionPerformed(evt);
            }
        });

        boutonCasting.setText("Casting");
        boutonCasting.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boutonCastingActionPerformed(evt);
            }
        });

        boutonEpisode.setText("Épisode");
        boutonEpisode.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boutonEpisodeActionPerformed(evt);
            }
        });

        boutonSaison.setText("Saison");
        boutonSaison.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boutonSaisonActionPerformed(evt);
            }
        });

        boutonGenre.setText("Genre");
        boutonGenre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boutonGenreActionPerformed(evt);
            }
        });

        boutonProduction.setText("Production");
        boutonProduction.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boutonProductionActionPerformed(evt);
            }
        });

        boutonScenariste.setText("Scénariste");
        boutonScenariste.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boutonScenaristeActionPerformed(evt);
            }
        });

        boutonPays.setText("Pays d'origine");
        boutonPays.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boutonPaysActionPerformed(evt);
            }
        });

        jLabel2.setText("Si des informations doivent être inséré dans d'autres tables que Série, veuillez vérifier que la série existe.");

        jLabel3.setText("Concernant les autres séries existantes toute les modifications sont possibles sur les autres tables.");

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(boutonUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(BoutonDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(boutonAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1)
                .addGap(18, 18, 18)
                .addComponent(boutonExit, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 648, Short.MAX_VALUE)
                .addGap(20, 20, 20))
            .addGroup(layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(boutonPays, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(boutonScenariste, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(listeSerie, javax.swing.GroupLayout.Alignment.LEADING, 0, 161, Short.MAX_VALUE)
                        .addComponent(boutonProduction, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(boutonGenre, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(boutonSaison, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(boutonEpisode, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(boutonSerie, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(boutonCasting, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 608, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 596, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(listeSerie, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(boutonSerie)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(boutonCasting)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(boutonEpisode)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(boutonSaison)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(boutonGenre)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(boutonProduction)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(boutonScenariste)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(boutonPays))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 389, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(boutonAdd)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(boutonExit))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(boutonUpdate)
                    .addComponent(BoutonDelete))
                .addGap(30, 30, 30))
        );

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

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

    private void listeSerieActionPerformed(java.awt.event.ActionEvent evt) {                                           
         listeSerie.addItemListener(new ItemChangeListener());
    }                                          

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

        /*this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);*/
    }                                          

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

    private void boutonScenaristeActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        /*try {   
            scenaristeTable SCT = new scenaristeTable(); SCT.setVisible(true); SCT.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        } catch (SQLException ex) {
            Logger.getLogger(TableCon.class.getName()).log(Level.SEVERE, null, ex);
        }*/
    }                                                

    private void boutonSerieActionPerformed(java.awt.event.ActionEvent evt) {                                            
        /*try {   
            serieTable TS = new serieTable(); TS.setVisible(true); TS.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        } catch (SQLException ex) {
            Logger.getLogger(TableCon.class.getName()).log(Level.SEVERE, null, ex);
        }*/

    }                                           

    private void boutonCastingActionPerformed(java.awt.event.ActionEvent evt) {                                              
        /*try {
            castingTable CT = new castingTable(); CT.setVisible(true); CT.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        } catch (SQLException ex) {
            Logger.getLogger(TableCon.class.getName()).log(Level.SEVERE, null, ex);
        }*/
    }                                             

    private void boutonEpisodeActionPerformed(java.awt.event.ActionEvent evt) {                                              
        /*try {
            episodeTable ES = new episodeTable(); ES.setVisible(true); ES.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);        // TODO add your handling code here:
        } catch (SQLException ex) {
            Logger.getLogger(TableCon.class.getName()).log(Level.SEVERE, null, ex);
        }*/
    }                                             

    private void boutonSaisonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        /*try {
            saisonTable ST = new saisonTable(); ST.setVisible(true); ST.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        } catch (SQLException ex) {
            Logger.getLogger(TableCon.class.getName()).log(Level.SEVERE, null, ex);
        }*/
    }                                            

    private void boutonGenreActionPerformed(java.awt.event.ActionEvent evt) {                                            
        /*try {
            genreTable GT = new genreTable(); GT.setVisible(true); GT.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        } catch (SQLException ex) {
            Logger.getLogger(TableCon.class.getName()).log(Level.SEVERE, null, ex);
        }*/
    }                                           

    private void boutonProductionActionPerformed(java.awt.event.ActionEvent evt) {                                                 
       /* try {
            productionTable PT = new productionTable(); PT.setVisible(true); PT.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        } catch (SQLException ex) {
            Logger.getLogger(TableCon.class.getName()).log(Level.SEVERE, null, ex);
        }*/
    }                                                

    private void boutonPaysActionPerformed(java.awt.event.ActionEvent evt) {                                           
        /*try {
            paysTable PST = new paysTable(); PST.setVisible(true); PST.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        } catch (SQLException ex) {
            Logger.getLogger(TableCon.class.getName()).log(Level.SEVERE, null, ex);
        }*/
    }                                          



    // Variables declaration - do not modify                     
    private javax.swing.JButton BoutonDelete;
    private javax.swing.JTable TableModel;
    private javax.swing.JButton boutonAdd;
    private javax.swing.JButton boutonCasting;
    private javax.swing.JButton boutonEpisode;
    private javax.swing.JButton boutonExit;
    private javax.swing.JButton boutonGenre;
    private javax.swing.JButton boutonPays;
    private javax.swing.JButton boutonProduction;
    private javax.swing.JButton boutonSaison;
    private javax.swing.JButton boutonScenariste;
    private javax.swing.JButton boutonSerie;
    private javax.swing.JButton boutonUpdate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JComboBox listeSerie;
    // End of variables declaration                   
}
EN

回答 1

Stack Overflow用户

发布于 2019-02-20 14:11:08

我不确定你遇到的确切问题是什么,但我认为这可能与你设置默认表模型并填充它的方式有关。

您的代码表明您的JTable只包含两列,因此您也可以在SQL字符串中指明所需的数据列:

代码语言:javascript
复制
public void itemStateChanged(ItemEvent event) {              
    Connection conn = null;
    Statement stm = null;
    ResultSet res = null;  
    PreparedStatement statement = null;
    try {
        if (event.getStateChange() == ItemEvent.SELECTED) {        
            Object item = event.getItem();
            if(item == "Série") {
                try {
                    System.out.println("Connecting to database");
                    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/module104MaximeJoly","root","root");
                    System.out.println("Connected to database");
                    stm = conn.createStatement();
                    ResultSet rs = stm.executeQuery("SELECT id_serie, nom FROM t_serie");

                    // Retrieve result set meta data. Column row 
                    // counts, Column Names, Column Data Types, etc
                    // can be retrieved from the rs meta data.
                    ResultSetMetaData rsmd = rs.getMetaData();
                    // Get default table model
                    DefaultTableModel dtm = (DefaultTableModel) TableModel.getModel(); 
                    // Clear the JTable first...
                    clearJTable(dtm);

                    while(rs.next()) {
                        Object[] row = new Object[rsmd.getColumnCount()];
                        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                            row[i - 1] = rs.getObject(i);
                            if (row[i - 1] == null) {
                                row[i - 1] = "";
                            }
                        }
                        dtm.add(row);
                    }
                }
                catch(Exception e) {
                    e.printStackTrace();      
                }
                finally {
                    try {                               
                        res.close();
                        stm.close();
                        conn.close();
                    }
                    catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }                   
    catch (Exception ex) {       
        Logger.getLogger(TableCon.class.getName()).log(Level.SEVERE, null, ex);
    } 
}

private void clearJTable(DefaultTableModel yourTableModel) {
    while (yourTableModel.getRowCount() > 0) {
        for (int i = 0; i < yourTableModel.getRowCount(); i++) {
            yourTableModel.removeRow(i);
        }
    }
}

我还添加了一个clearJTable()方法。您当然可以根据结果集使JTable添加或删除列,但是您需要为此添加更多方法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100003113

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档