简体   繁体   中英

Change JtextField depending on JcomboBox Selected using database data - Java

I am having trouble getting data from data base showing how it should on a project I have.

I am after getting data from datbase then showing in the program. When a item is selected in combo box it will show the corresponding data in a JtextField.

Here is my current code in Java

public Clientes() {


    initComponents();


     LigacaoBD ligaDB = new LigacaoBD();
     Connection con = ligaDB.obterLigacao();

     String query=null;
     Statement xpto;


    try {
        xpto = con.createStatement();

        query = "SELECT cod_postal, localidade FROM codigospostais";
     ResultSet rs = xpto.executeQuery(query);
     while (rs.next()){

         jtcpostal_cliente.addItem(rs.getString(1));


         jtfcodpostal_cliente.setText(rs.getString(2));
         jtfcodpostal_cliente.validate();





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



}

Currently I can get the combobox working but it wont show me in the JtextField the data corresponding to the combobox.

数据库:

    cb.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent arg0) {
            String s = String.valueOf(arg0.getItem());
            tf.setText(s);
        }
    });

this will always change the text of you textfield to the text you selected in your combobox. i think this is what you were looking for. if not, please tell me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM