Pick up the selected item in Jcombobox

Asked

Viewed 7,551 times

1

How do I get the user selected item on this Combobox?

opcaoBusca.setModel(new DefaultComboBoxModel(new String[] {"Op\u00E7\u00E3o da Busca", "N\u00FAmero do Pedido"}));

        entBusca = new JFormattedTextField();
        entBusca.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                entBusca.setText("");
            }
        });
        entBusca.setEnabled(false);

        ListaBox = new JComboBox<String>();
        ListaBox.addItem("Selecione");
        try {  
            Class.forName("oracle.jdbc.OracleDriver");
            Connection con = DriverManager.getConnection(
                    "jdbc:oracle:thin:@192.168.1.1:1521:banco1","root","root");

            Statement stmt = con.createStatement();
            ResultSet RS = null;
            RS = stmt.executeQuery("select codplpag from pcplpag  "); 

            while(RS.next()){  
                ListaBox.addItem(RS.getString("codplpag"));  
                //String codplpag  = RS.getString("codplpag");
                //System.out.println("saida de dados" +codplpag);

            }  

            stmt.close();  
            con.close();  
        }  

        catch(SQLException e)  
        {  
            JOptionPane.showMessageDialog(this,"Erro Cmdo SQL "+e.getMessage());  
        }  
        catch(ClassNotFoundException e){  
            JOptionPane.showMessageDialog(this,"Driver não encontrado");  
        }  

1 answer

5


To get the selected index:

int indiceSelecionado = seuComboBox.getSelectedIndex();

Or, to get by item (value/word):

String itemSelecionado = seuComboBox.getSelectedItem().toString();

Another way is to use one ItemListener to perform some action when the user selects a different option in JComboBox. For this, there is the method getItem().

Sample code:

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class ComboBox extends JFrame {

    public ComboBox(){
        JComboBox combobox = new JComboBox();
        combobox.addItem("Cachorro");
        combobox.addItem("Gato");
        combobox.addItem("Peixe");

        // Listener para 'fazer algo' sempre que for selecionada uma opção no JComboBox
        combobox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED) // para evitar duplicações
                    System.out.println("Você escolheu a opção " + e.getItem());
            }
        });

        // Propriedades do JFrame
        setSize(150, 100);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        getContentPane().add(combobox);
    }

    public static void main(String[] args) {
        new ComboBox().setVisible(true);
    }
}
  • Reindeer when I put it that way, it does not show anything in the output but the name Selection //---code------- while(RS.next())' Listabox.addItem(RS.getString("codplpag"); //String codplpag = RS.getString("codplpag"); } String selected = Listabox.getSelectedItem(). toString(); System.out.println("this is the item: " + selected);

  • and that’s exactly what’s happening!!! how I change it I didn’t understand it very well.

  • Poxa Renam, very good guy was worth even now just one more question as I do to get this value that was selected to save in the database through an update ? -code- int record = stmt.executeUpdate("update pcpedc set codplpag = "in case the selected option would be here" + " Where numped=" + consPCPEDC);

  • 1

    Renan thank you very much brother, it was even worth a strong hug Brow.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.