Enter em jcombobox editavel, como fazer?

5 respostas
DAREK6920

Ola galera, sou novo por aqui e também novo em java. Estou usando o NetBeans e tenho um problema que deve até ter uma solução simples, porém não atino qual seja. Criei um jcombobox editavel com o nome de Lista. O que pretendo é que ao digitar um texto nele um metodo seja chamado e busque no arquivo todos os registros semelhantes e liste-os no roprio combo. O problema é que não sei como ele vai identificar a tecla enter para fazer a busca e separar o que é busca do que é seleção propriamente dita. Quando coloco o metodo em performedaction ele simplesmente faz uma primeira busca e sem seguida faz automaticamente uma segunda em cima do texto que aparece como resultado.
Aqui vai o codigo para qu epossam entender melhor:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * nsimples.java
 *
 * Created on 11/02/2011, 16:31:12
 */

package ta01;

import com.mysql.jdbc.PreparedStatement;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Dario
 */
public class nsimples extends javax.swing.JFrame {

    /** Creates new form nsimples */
    public nsimples() {
        setTitle("Cadastro Nacional de Atividades Empresariais");
        setIconImage(new ImageIcon(getClass().getResource("/imagens/STAR5.gif")).getImage());
        setLocationRelativeTo(null);
        this.setExtendedState(JFrame.NORMAL);
        getContentPane().setBackground(Color.black);
        initComponents();
 
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        atividade = new javax.swing.JLabel();
        r11 = new javax.swing.JLabel();
        lista = new javax.swing.JComboBox();

        jPanel1.setBackground(new java.awt.Color(0, 0, 0));
        jPanel1.setForeground(new java.awt.Color(255, 255, 255));
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        atividade.setBackground(new java.awt.Color(0, 0, 0));
        atividade.setForeground(new java.awt.Color(255, 255, 255));
        jPanel1.add(atividade, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 80, 340, 70));

        r11.setBackground(new java.awt.Color(0, 0, 0));
        r11.setForeground(new java.awt.Color(255, 255, 255));
        jPanel1.add(r11, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 10, 80, 20));

        lista.setBackground(new java.awt.Color(0, 0, 0));
        lista.setEditable(true);
        lista.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N
        lista.setForeground(new java.awt.Color(255, 255, 255));
        lista.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        lista.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listaActionPerformed(evt);
            }
        });
        lista.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                listaInputMethodTextChanged(evt);
            }
        });
        lista.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                listaKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                listaKeyTyped(evt);
            }
        });
        jPanel1.add(lista, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 340, -1));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 367, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(23, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void listaActionPerformed(java.awt.event.ActionEvent evt) {
       
    }

    private void listaInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
        // TODO add your handling code here:
    }

    private void listaKeyPressed(java.awt.event.KeyEvent evt) {
      JOptionPane.showMessageDialog(this,evt.KEY_PRESSED);
    }

    private void listaKeyTyped(java.awt.event.KeyEvent evt) {
      
    }
   
//inicio do metodo busca
    private void Busca(String codex) throws ClassNotFoundException, SQLException {
        java.sql.Connection con;
        java.sql.Statement st;
        java.sql.ResultSet rs;
        String seletor = "";
        String fator = "";
        //if (new Double(codex).isNaN()){
          fator = "%" + fator + "%";
          seletor = "Select * from cnae where atividade like " + "'" + fator + "'";
        //  }
        //else{
        //  seletor = "Select * from cnae where cnae1 = " + "'" + codex + "'" + "";
        //  }
        
        con = funcoes.getConnection();
        st=con.createStatement();
        rs = st.executeQuery(seletor);
        lista.removeAllItems();
        while (rs.next()){
            String tt = rs.getString("atividade");
            lista.addItem(tt);
        }
    }
//fim do metodo busca    
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new nsimples().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel atividade;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JComboBox lista;
    private javax.swing.JLabel r11;
    // End of variables declaration

}

5 Respostas

ViniGodoy

Ao postar códigos, use a tag code:

Senão fica difícil de ler.

DAREK6920

Desculpe, realmente sou novo por aqui. Se tiver mais algum problema é só falar que tento corrigir

vanderlanio

Tente usar o addKeyListener :lol:
Uma outra dica e usar o swingx, ele tem um auto-complete !

DAREK6920

Ola, de novo.
Tentei criar um choice no lugar do jcombobox mas ele não é editavel então não serve para o que eu quero. Porem…
O danado do choice aceita o keyevent numa boa. Meu problema é fazer o jcombobox responder a um enter e a partir dai ser carregado a partir de opções num arquivo.
Para só então poder aceitar o getselecteditem.
Estou usando o NetBeanr 6.91 e ele me dá o auto-complete normalmente, porem, nenhuma luz no fim do tunel.
Alguem pode me explicar porque o jcombobox so aeita o performedaction e não o keypressed ou keytyped ?

romulo_wan

isso eu quero saber Tbm.

só que aqui acho q nem o Performed tá pegando

Criado 14 de fevereiro de 2011
Ultima resposta 7 de jun. de 2011
Respostas 5
Participantes 4