Pick up the selected item in Jcombobox

1

How do I get the item selected by the user in 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");  
        }  
    
asked by anonymous 08.01.2015 / 11:33

1 answer

4

To get the selected index:

int indiceSelecionado = seuComboBox.getSelectedIndex();

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

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

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

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);
    }
}
    
08.01.2015 / 11:44