Aide java JCombobox,

Résolu
supupoff Messages postés 312 Date d'inscription   Statut Membre Dernière intervention   -  
hanaeb Messages postés 2 Date d'inscription   Statut Membre Dernière intervention   -
Bonjour,

J'arrive a remplir un JCombobox a l'aide de requete sql

      s = c.createStatement();
			rs =s.executeQuery("SELECT num,nom FROM  projet");
			while(rs.next()){
			combo1.addItem(rs.getString("nom"));

je voudrai une fois un nom est selectionne ,recuperer le numero qui servira d'identifiant le projet pour l'autre traitement,

Aide svp,

merci de m'aide
Merci d'avance
A voir également:

4 réponses

arth Messages postés 9374 Date d'inscription   Statut Contributeur Dernière intervention   1 293
 
Mais le numéro existe déjà?

Et si oui où est-il stocké?
0
supupoff Messages postés 312 Date d'inscription   Statut Membre Dernière intervention   34
 
le numéro est stocké dans Base de donnée dans Table projet, ;)
0
KX Messages postés 16761 Date d'inscription   Statut Modérateur Dernière intervention   3 020
 
Il y a plusieurs manière de faire, par exemple en stockant les num dans une map et les associer aux noms :

final TreeMap<String,Integer> map = new TreeMap<String,Integer>();
final JComboBox<String> combo1 = new JComboBox<String>();

s = c.createStatement();
rs =s.executeQuery("SELECT num,nom FROM  projet");
while(rs.next())
{
	int num = rs.getInt("num");
	String nom = rs.getString("nom");
	combo1.addItem(nom);
	map.put(nom,num);
}

combo1.addActionListener(new ActionListener()
{
	public void actionPerformed(ActionEvent e)
	{
		String nom = combo1.getSelectedItem();
		int num = map.get(nom);
		System.out.printf("(%s,%d) selected",nom,num);
	}
});

Il est également tout à fait possible aussi d'ajouter autre chose qu'un String à un JComboBox, en particulier on pourrait ajouter un objet qui stockerai tes deux informations. C'est alors la méthode toString qui sera utilisé pour l'affichage.

class Id
{
	public final String nom;
	public final int num;
	
	public Id(String nom,int num)
	{
		this.nom = nom;
		this.num = num;
	}
	
	public String toString()
	{
		return nom;
	}
}

final JComboBox<Id> combo1 = new JComboBox<Id>();

s = c.createStatement();
rs =s.executeQuery("SELECT num,nom FROM  projet");
while(rs.next())
{
	int num = rs.getInt("num");
	String nom = rs.getString("nom");
	combo1.addItem(new Id(nom,num));
}

combo1.addActionListener(new ActionListener()
{
	public void actionPerformed(ActionEvent e)
	{
		Id id = combo1.getSelectedItem();
		System.out.printf("(%s,%d) selected",id.nom,id.num);
	}
});
0
supupoff Messages postés 312 Date d'inscription   Statut Membre Dernière intervention   34
 
Merci beaucoup KX, tu m'aide beaucoup, je vais essayer et je revenir pour tu dire c que passe
0
supupoff Messages postés 312 Date d'inscription   Statut Membre Dernière intervention   34
 
Salut,

je créer cette méthode pour l'affichage du liste user

 public void fillJCBOX1()
  {
      connexion c = new connexion();
        try {
            Statement s ;
             ResultSet rs ;
           s = c.createStatement(); // indiqué das l'erreurs si j'enlève le try catch : 204
     rs =s.executeQuery("SELECT * FROM  user"); // ligne indiqué  l'erreur : 205
  
     while(rs.next())
     {
             int num = rs.getInt("id");
             String nom = rs.getString("Nom");
             String prenom = rs.getString("Prenom");
             System.out.println("dans jcombo"+prenom);
             jComboBox1.addItem(new Id(nom,prenom,num));
     }  } catch (Exception ex) {
             ex.printStackTrace();
        }
  }


retourn les erreurs suvantes :

java.lang.NullPointerException
	at JfrAdministrator.fillJCBOX1(JfrAdministrator.java:205)
	at JfrAdministrator.formWindowOpened(JfrAdministrator.java:1366)
	at JfrAdministrator.access$000(JfrAdministrator.java:20)
	at JfrAdministrator$1.windowOpened(JfrAdministrator.java:311)
	at java.awt.Window.processWindowEvent(Window.java:2048)
	at javax.swing.JFrame.processWindowEvent(JFrame.java:296)
	at java.awt.Window.processEvent(Window.java:2009)
	at java.awt.Component.dispatchEventImpl(Component.java:4861)
	at java.awt.Container.dispatchEventImpl(Container.java:2287)
	at java.awt.Window.dispatchEventImpl(Window.java:2719)
	at java.awt.Component.dispatchEvent(Component.java:4687)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
	at java.awt.EventQueue.access$200(EventQueue.java:103)
	at java.awt.EventQueue$3.run(EventQueue.java:688)
	at java.awt.EventQueue$3.run(EventQueue.java:686)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
	at java.awt.EventQueue$4.run(EventQueue.java:702)
	at java.awt.EventQueue$4.run(EventQueue.java:700)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
BUILD SUCCESSFUL (total time: 10 seconds)



et si j'enlève le try catch
J'obtient les erreurs suivant

Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - unreported exception java.sql.SQLException; must be caught or declared to be thrown
 
	at JfrAdministrator.fillJCBOX1(JfrAdministrator.java:204)
	at JfrAdministrator.formWindowOpened(JfrAdministrator.java:1364)
	at JfrAdministrator.access$000(JfrAdministrator.java:20)


Merci beaucoup,
0
KX Messages postés 16761 Date d'inscription   Statut Modérateur Dernière intervention   3 020
 
Java oblige que toutes les exceptions soient traitées. Tu as toute une partie de ton code qui génère des SQLException, tu es donc obligé de mettre des try/ctach pour les traiter (il n'est donc pas question de les enlever)

Pour le NullPointerException, je ne comprends pas. Si tes lignes sont correctes, la on a "s" qui vaut "null", or il n'est pas prévu que createStatement() puisse renvoyer "null"...
0
supupoff Messages postés 312 Date d'inscription   Statut Membre Dernière intervention   34
 
Merci pour ta réponse,
j'ai crée méthode selection dans class connexion
 public ResultSet selection(String req){ 
        ResultSet res = null; 
         
        try{ 
            rst = con.createStatement(); 
            res = rst.executeQuery(req); 
            res.beforeFirst(); 
        } catch(SQLException er){ 
            System.out.print("error sql : "+er); 
        } 
         
        return res; 
    } 

et je fait appel
rs =c.selection("SELECT * FROM user");

et sa cool bien

je veux passé maintenant au deuxième étape ( l'insertion dans la base ), je vais essayer et je revenir pour tu dire ce que passe, merci,
0
supupoff Messages postés 312 Date d'inscription   Statut Membre Dernière intervention   34
 
Bon l'insertion sa cool bien aussi merci KX pour l'idée et pour l'aide,

j'ai un petit souci :

j'ai une JTable qui contient resultat d'une select, je veux lorsque je selectionne un enregistrement du Jtable s'affiche dans le champs du formulaire,

j'ai créer dans Jtable un champs caché ( id ) pour le traitement,

j'ai utilise pour les JTextField
int rec = this.jTable3.getSelectedRow();      
this.jTextField17.setText(jTable3.getValueAt(rec, 0).toString());

..
mais pour JCombobox, je veux qu'il soit ajouter au début du liste déjas dans JCombobox mais j'arrive pas ' ajouter sélection que si je remove All Item,
String NM = this.jTable3.getValueAt(rec, 2).toString();      
String PR =jTable3.getValueAt(rec, 3).toString();      
 Récupéré champ caché    
  Int  NU  =this.jTable3.getValueAt(rec, 4).toString();  // ici erreur !!       

this.jComboBox1.removeAllItems();      
 this.jComboBox1.addItem(new Id(NM,PR,NU)); 
0
hanaeb Messages postés 2 Date d'inscription   Statut Membre Dernière intervention  
 
Bonjour , s'il vous plait puisque vous êtes parvenu à résoudre ce problème donc vous saurez a priori comment faire pour la mise à jour d'un Jtable à partir de la sélection de mon jcombobox . Je m'explique: j'ai un jtable qui affiche toutes les informations concernant un archive par service et il y'a plusieurs services. mon jcombobox contient les service: je veux afficher tous les archives qui sont affectés à un service donnée une fois je sélectionne le service sur le jcombobox ... AIDEZ moi svvvp je fais une application pour mon stage et il me reste plus que 3 jours pour l'achever :( :(
0
hanaeb Messages postés 2 Date d'inscription   Statut Membre Dernière intervention  
 
le problème est que l'affichage sur le jtable se fait juste pour l'item sélectionné par défaut une fois je sélectionne un autre aucun changement ne se fait .. :/ quelqu'un pourra t'il m'aider svp ?!!
0