Affichage données MySQL dans JTable Java à partir d'un JButton

Signaler
-
 fallpoint -
Salut !!
moi je fait le procedure qui fait l'ajout des donné au base de donné
je veux lorsque clic sur bouton Ajouter, afficher les données qui je l'inseré sur le table !! et aussi losque clic sur boutton Afficher, affiche tout les données qui sont dans le base sur la table !!

[del]
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Introduction;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.sql.DriverManager;
import javax.swing.JOptionPane;

/**
*
* @author AymenKn
*/
public class FromStagiaire extends javax.swing.JFrame {

/**
* Creates new form FromStagiaire
*/
public FromStagiaire() {
initComponents();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jPanel1 = new javax.swing.JPanel();
txt_mat = new javax.swing.JTextField();
txt_nom = new javax.swing.JTextField();
txt_prenom = new javax.swing.JTextField();
txt_email = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
table_stg = new javax.swing.JTable();
btn_ajouter = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Adobe Arabic", 1, 10), new java.awt.Color(51, 51, 255))); // NOI18N
jPanel1.setForeground(new java.awt.Color(51, 153, 255));

jLabel1.setText("Mat :");

jLabel2.setText("Nom :");

jLabel3.setText("Prenom :");

jLabel4.setText("Email :");

table_stg.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 [] {
"Mat", "Nom", "Prenom", "Email"
}
));
jScrollPane1.setViewportView(table_stg);

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

jButton1.setText("Afficher");

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(btn_ajouter)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING))
.addComponent(jLabel2)
.addComponent(jLabel1))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txt_mat)
.addComponent(txt_nom)
.addComponent(txt_prenom)
.addComponent(txt_email, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 481, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(28, 28, 28))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_mat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_nom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_prenom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_ajouter)
.addComponent(jButton1))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);

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

//connexion a la base de donné
private void connexion (){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/gestion stagiaire", "root", "");
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Erreur connexion\n"+e.getMessage());
}
}

//Ajouter stagiaire
private void btn_ajouterActionPerformed(java.awt.event.ActionEvent evt) {
try{
connexion ();
String sql = "insert into stagiaire values(?,?,?,?)";
pst = (PreparedStatement) con.prepareStatement(sql);
pst.setString(1,txt_mat.getText());
pst.setString(2,txt_nom.getText());
pst.setString(3,txt_prenom.getText());
pst.setString(4,txt_email.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Ajouter stagiaire avec succés");
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Erreur ajouter stagiaire\n"+e.getMessage());
}
}


/**
* @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(FromStagiaire.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FromStagiaire.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FromStagiaire.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FromStagiaire.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 FromStagiaire().setVisible(true);
}
});
}

// Déclaration des variables.
private Connection con;
private PreparedStatement pst;
private int mat,i;
private String nom ,prenom,email;

// Variables declaration - do not modify
private javax.swing.JButton btn_ajouter;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable table_stg;
private javax.swing.JTextField txt_email;
private javax.swing.JTextField txt_mat;
private javax.swing.JTextField txt_nom;
private javax.swing.JTextField txt_prenom;
// End of variables declaration
}/del
A voir également:

3 réponses


j'ai travaillé sous eclipse , si vous pouvez m'aider de faire une bouton d'affichage et modification de données qui sont dans le base sur la table,Je serai reconnaissant à vous
Merci


assiasunchine
Bonjour si tu arrive à insérer dans la base de données l'affichage dans le Jable devient facile essais ce bout de code sa devrai marcher
            try{
                // requête qui selection toute les données de la table
        String sql="select * from Nom_de_la_Table";
                ResultSet rs=My_ExecuteQuery(sql);
                int i=0;
                int k=0;
                if(rs.next()){
                    rs.last();
                    k=rs.getRow();
                    rs.beforeFirst();
                }
               Object[][] t=new Object[k][3];
               // met le resultat de la requete dans un tableau
                while (rs.next()){
                   
                   t[i][0]=rs.getString(1);
                   t[i][1]=rs.getString(2);
                   t[i][2]=rs.getString(3);           
                    i++;
                }
               
                rs.close();
                // affiche le tableau dans le jtable
         final String columnNames[] = {"nom1","nom2","nom3"};
         jTable1.setModel(new DefaultTableModel(t,columnNames));
         ListSelectionModel listMod =  jTable1.getSelectionModel();
         listMod.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         listMod.addListSelectionListener(jTable1);
                 

    }
    catch(Exception ex){ 
        ex.printStackTrace();
    }

Salut,

Ce serait grandement plus simple si tu prenais la peine de coder toi même les interfaces graphiques plutôt que de passer par des outils qui te pondent le code tout prêt fait. Non seulement ce code est désorganisé, mais en plus il est illisible et difficilement maintenable. Après il ne faut pas s'étonner que tu n'arrives pas à faire quelque chose dessus.

Par curiosité, quel logiciel utilises-tu ?


--
Pylouq
Heureux sont ceux qui lisent le Réglement, ils ne finiront peut-être pas au bûcher.