JAVA: How to populate a JComboBox...

Solved
Yserman -  
 chaimae -
Here is the translation: Hello everyone

My problem is that I need to populate a JComboBox with the values from one of the columns in one of my tables.

It should be quite simple, but...

Thanks in advance

16 answers

  1. Bouassida
     
    Once connected to the database: these instructions will allow you to fill your combo
    (I tried it and it worked)
    /*------------------------- Method to fill the jComboBox ---------------------------*/
    void fill_Jcomb() { String req= "SELECT Field_Name1,Field_Name2 FROM Table_Name ORDER BY Field_Name1"; Statement stmt; try { stmt = con.createStatement(); ResultSet res = stmt.executeQuery(req); while(res.next()){ jComboName.addItem(res.getString(column index)); /* the name of the jComboBox is jComboName and <column index> is the index of the column you want to display in the combobox, it can take one of the values 1,2 . . } res.close(); } catch (SQLException e) { e.printStackTrace(); } }
    //End fill_Jcomb()
    14
    1. chaimae
       
      Thank you, Bouassida.
      0
  2. yserman
     
    ah I found it thank you it works

    the code:

    choixfournisseur = new JComboBox();
    choixfournisseur.setMaximumRowCount(5);
    choixfournisseur.setBounds(550, 120, 150, 30);
    choixfournisseur.setBackground(Color.WHITE);
    cont.add(choixfournisseur);

    Vector listenom=AccesBD.creerVecteur1Colonne("SELECT distinct Nom from Fournisseur ");
    choixfournisseur.removeAllItems();
    for(int i=0; i<listenom.size(); i++)
    choixfournisseur.addItem((String)(listenom.elementAt(i)));
    3
  3. philtrain
     
    Hello,

    If we look at the documentation for the JComboBox class, we find the following parameters:
    - for the constructor: nothing, a ComboBoxModel, an array of Object or a Vector;
    - for the methods: an Object.

    See: http://java.sun.com/j2se/1.5.0/docs/api/

    From there, you just need to retrieve the data from your table in one of the forms mentioned above, and use either one of the constructors or the method.

    There is an excellent tutorial on the Sun website: "How to Use Combo Boxes"

    See you soon

    --
    -- O espirito da liberdade --
    2
  4. triou
     
    Thank you for these messages, they helped me a lot.
    2
  5. maily Posted messages 7560 Status Contributor 453
     
    So, you're using a Recordset object?

    String query = "SELECT COF_NAME, PRICE FROM COFFEES"; ResultSet rs = stmt.executeQuery(query); JComboBox j = new JComboBox(); while (rs.next()) { rs.getString("ColumnName"); j.addItem(rs.getFloat("PRICE")); }


    ps: I've never dealt with JComboBoxes and I couldn't remember the syntax for queries! Long live the Java doc and the Sun website
    References:
    http://java.sun.com/j2se/1.4.2/docs/api/index.html
    http://java.sun.com/docs/books/tutorial/jdbc/basics/retrieving.html
    --
    Maily
    Ragondin, go to the corner!
    1
  6. manana007
     
    Bonjour,
    I am trying to fill a jCombox from a database (MySQL server) but when displaying the interface I have an infinite loop that I can't correct.
    Please help me to solve this problem (I am working in NetBeans).
    Here is the code:
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    package asterisk_teste;

    /**
    *
    * @author
    */
    import java.sql.*;
    import java.io.*;
    import java.util.*;
    import java.sql.DriverManager;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.ComboBoxModel;
    import javax.swing.DefaultListModel;
    import javax.swing.event.ListDataListener;
    public class SQLrequete

    { public static Administrateur ad =new Administrateur();
    public ResultSet rs1 ;

    public SQLrequete() throws SQLException
    {
    try {
    Connection connection;
    BaseDeDonnee basededonnee = new BaseDeDonnee ();
    rs1=basededonnee.rs;

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

    // ad.Terminal.setModel(model);
    // ad.setVisible(true);

    }
    public static void main(String[] args) throws SQLException
    { //SQLrequete teste =new SQLrequete();

    try {
    //Connection connection;
    BaseDeDonnee basededonnee = new BaseDeDonnee ();
    // teste.rs1=basededonnee.rs;
    // teste.model=basededonnee.getListModelFromResultSet(basededonnee.rs);

    } catch (ClassNotFoundException ex) {

    Logger.getLogger(SQLrequete.class.getName()).log(Level.SEVERE, null, ex);
    }

    //teste.ad.Terminal.setModel(model);
    // teste.ad.setVisible(true);

    }

    }
    class BaseDeDonnee
    {
    public Connection connection = null ;
    public ResultSet rs ;
    public Statement stmt;
    public String requete;
    public Administrateur ad =new Administrateur();
    public DefaultListModel model;
    public BaseDeDonnee() throws ClassNotFoundException, SQLException
    { System.out.println("\n+++++++++++++++++++");
    connexion();
    System.out.println("\n++++++++++++++++++++++");
    stmt = connection.createStatement();
    requete = "SELECT * FROM terminal ORDER BY Num ASC LIMIT 0 , 30";
    System.out.println("\n=======================");
    rs=affichage(requete);
    this.getModelFromResultSet(affichage(requete));
    ad.setVisible(true);
    System.out.println("\n====================");
    fin_connexion();
    }

    // Connexion à la base de donnees
    public void connexion () throws ClassNotFoundException, SQLException
    {
    try
    {
    // Chargement des drivers SQL
    System.out.println("\n------------------------");
    System.out.println("Connexion au driver JDBC.");
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    System.out.println("Driver com.mysql.jdbc.Driver chargé.");
    }
    catch (ClassNotFoundException a)
    {
    System.out.println ("Driver non trouve.");
    }
    catch (Exception b)
    {
    System.out.println ("Problème sur chargement de driver JDBC.");
    }

    try
    {
    // Etablissement de la connexion avec la base
    String url1 = "jdbc:mysql://127.0.0.1:3306/Asteriskteste";
    connection = DriverManager.getConnection(url1,"root","bandia007");
    System.out.println("Connexion a la base établie.");
    System.out.println("------------------------\n");
    }
    catch (SQLException c)
    {
    System.out.println ("Connexion refuse ou base inconnu.");
    }
    catch (Exception d)
    {
    System.out.println ("Problème sur connexion.");
    }
    }
    public ResultSet affichage(String req)
    {
    // ResultSet rs = null;
    int i=1;

    try
    {
    //Exécution des requêtes
    //requete = "INSERT INTO `Terminal` ( `Terminal_nom` ) VALUES ( 'EGG' )";
    //requete = "SELECT * FROM terminal ORDER BY Num ASC LIMIT 0 , 30";
    rs = stmt.executeQuery(requete);
    // Statement stmt = connection.createStatement() ;
    //String queryString = "INSERT INTO terminal ( Nom ) VALUES ( 'softphone_mouna' )";
    // String nom="401";
    // String nom1="400";
    // String queryString = "select Num from terminal " ;
    // String queryString1 =req;

    //int update = stmt.executeUpdate(queryString);
    //int update1 = stmt.executeUpdate(queryString1);
    System.out.println (rs);
    while (rs.next())
    {
    System.out.println("Nom : " +rs.getString(1));
    System.out.println("Num : " +rs.getString(2));
    System.out.println("State :" +rs.getString(3));
    System.out.println(""+i);
    i++;

    }

    }
    catch (SQLException d)
    { d.getSQLState();
    d.getErrorCode();
    System.out.println ("Problème la requete.");
    System.out.println ("Problème la requete." +d.getErrorCode()+d.getSQLState());
    }
    return rs;
    }
    public void getModelFromResultSet(ResultSet rs) throws SQLException {
    ComboBoxModel model = new ComboBoxModel() {

    public void setSelectedItem(Object anItem) {
    throw new UnsupportedOperationException("Not supported yet.");
    }

    public Object getSelectedItem() {
    throw new UnsupportedOperationException("Not supported yet.");
    }

    public int getSize() {
    throw new UnsupportedOperationException("Not supported yet.");
    }

    public Object getElementAt(int index) {
    throw new UnsupportedOperationException("Not supported yet.");
    }

    public void addListDataListener(ListDataListener l) {
    throw new UnsupportedOperationException("Not supported yet.");
    }

    public void removeListDataListener(ListDataListener l) {
    throw new UnsupportedOperationException("Not supported yet.");
    }
    };
    while (rs.next()) {
    rs.getString("NomDeLaColonne");
    ad.NumDial.addItem(rs.getString(1));
    }

    }
    public void fin_connexion()
    {
    try
    {
    // Fermeture de la connexion
    connection.close();
    System.out.println("\n------------------------");
    System.out.println ("Fermeture de connexion.");
    System.out.println("------------------------\n");
    }
    catch (Exception d)
    {
    System.out.println ("Problème sur la fermeture de connexion.");
    }
    }
    }
    Thank you in advance.
    1
  7. maily Posted messages 7560 Status Contributor 453
     
    Hello!

    Which table? Which column? From a database? Which database?

    --
    Maily
    Beaver, go to the corner!
    0
  8. Yserman
     
    The table is called "Supplier," and the column is called "Name" from the database "StockDB."
    0
    1. maily Posted messages 7560 Status Contributor 453
       
      Which DBMS?
      Have you already managed to connect to your database? Do you have the appropriate library?
      --
      Maily
      Ragondin, go to the corner!
      0
  9. yserman
     
    yes yes I am connected to my database, I created it with Access and I code in SQL

    it's just to retrieve the values from the column to put them in my JComboBox
    0
  10. maily Posted messages 7560 Status Contributor 453
     
    Are you connected to your database with Java? Did you use JDBC?
    --
    Maily
    Ragondin, go to the corner!
    0
  11. yserman
     
    Do I need to import a class to use an object of type ResultSet?
    0
  12. john
     
    What a useless email!

    What table? What column? From a database? Which database?

    Connect to the database, the table, and the column you want.
    Using a PrepareStatement.

    Iterate over the ResultSet object you obtain and collect the values of your column.

    Fill a Vector object with them.

    And instantiate your ComboBox. There you go, that's it.
    And if you want to be professional, use Apache common-dbutils (for database access) and Apache commons-beansutils for the dynamic creation of a combo, a table, or whatever, since the latter allows you to dynamically create a bean using the ResultSet as a parameter.
    0
    1. lolita_ch Posted messages 1 Status Member
       
      Hello!!

      If anyone has an example to retrieve the elements from a column and put them in a database, please write it to me
      I've tried a lot of things but it doesn't work

      thanks in advance
      0
  13. yakoviano Posted messages 9 Status Member
     
    I have a list box and I want to put its items in a JTable.
    0
  14. manjava
     
    Hello,

    Following your discussion regarding the JComboBox, I want to know how to fill a JTable based on the selection of an element from the JComboBox:
    I want to explain that I have two tables in the MySQL database: table forme (Code_f, Nom_f), table Produit (Code_p, Code_f, .......)
    the JComboBox is filled with a Nom_f, and when I select from the JComboBox, a JTable should display the corresponding Nom_f.

    This is my problem; I am trying with AbstractTableModel, but it’s not working. I don't know how to do it, I need an idea, please.

    Thank you, Best regards.
    0
  15. omiss
     
    Hello
    I have a problem with the JCombobox instruction and I can't find the solution, please help me

    The problem is that I have a JCombobox filled with SQL databases and I want that when I select a database from the JCombobox, the connection will change like a query analyzer tool
    Thank you
    0