Como usar o JComboBox

2 respostas
H

E ai galera blz? Meu programa está funcionando bem, mas eu apenas para aprender mais gostaria de adicionar o JComboBox, mas eu não sei como é a sintaxe.Já li a respeito mas não entendi muitos os exemplos. eu tenho uma classe encapsulada aonde eu puxo os dados. a classe é carro. Vou postar meu programa aqui. Abraço

public class P3 extends Generico implements ActionListener
{
Carro c1[];
int count=0;



    public  P3 ()

{
  super();
        String[] cb= {"civic","Corolla","Vectra","Fusion","Gol"};


        this.jButton4.setText("Maior Ano");
        this.jButton5.setText("Maior Valor");
        jButton1.setVisible(false);
        jButton2.setVisible(false);
        jButton3.setVisible(false);
        jButton4.addActionListener(this);
        jButton5.addActionListener(this);
        jButton6.addActionListener(this);
        jButton7.addActionListener(this);
        jButton8.addActionListener(this);
        jComboBox1.addActionListener(this);

}
void setCarro(Carro[] p)
   {
        c1 = p;
    }

    public void actionPerformed(ActionEvent e)
    {
        int Maior;
        int MaiorV = 0;
        int MaiorValor;
        int MaiorA=0;
        if(e.getSource()==jButton5)
        {
            for( int x =0; x<c1.length; x++)
            {
                if(c1[x].getValor()>MaiorA)
            
                MaiorA = c1[x].getValor();

            }
            jTextField3.setText( Integer.toString(MaiorA));
             jTextField2.setText("");
        }
        else
            if(e.getSource()==jButton4)
       {
            for(int x=0; x<c1.length; x++)
            {
                if(c1[x].getAno()>MaiorV)
                {
                   MaiorValor = x;
                   MaiorV = c1[x].getAno();
                }
            }
             jTextField2.setText( Integer.toString(MaiorV));
             jTextField3.setText("");
         }

            if(e.getSource() == jButton6)
            
            for(int x=0; x<c1.length-1; x++)
            {
                for(int y=x+1; y<c1.length; y++)
                {
                    if(c1[x].getAno() > c1[x].getAno())
                    {
                        Carro aux;
                        aux = c1[x];
                        c1[x] = c1[y];
                        c1[y] = aux;
                    }
                }
                
               String aux ="";
               for(int z=0; z<c1.length; z++)
               aux += c1[z].getAno()+ "\n";
              JOptionPane.showMessageDialog(this, "Vetor ordenado por Ano: \n" + aux);
              
        }
            if(e.getSource()==jButton7)
            {
                 for(int x=0; x<c1.length-1; x++)
            {
                for(int y=x+1; y<c1.length; y++)
                {
                    if(c1[x].getModelo().compareTo(c1[x].getModelo())>0)
                    {
                        Carro aux;
                        aux = c1[x];
                        c1[x] = c1[y];
                        c1[y] = aux;
                    }
                }

               String aux ="";
               for(int z=0; z<c1.length; z++)
               aux += c1[z].getModelo()+ "\n";
              JOptionPane.showMessageDialog(this, "Vetor ordenado por Modelo: \n" + aux);

        }

     }
          if(e.getSource()==jButton8)
          {
                   for(int x=0; x<c1.length-1; x++)
            {
                for(int y=x+1; y<c1.length; y++)
                {
                    if(c1[x].getValor() > c1[x].getValor())
                    {
                        Carro aux;
                        aux = c1[x];
                        c1[x] = c1[y];
                        c1[y] = aux;
                    }
                }

               String aux ="";
               for(int z=0; z<c1.length; z++)
               aux += c1[z].getValor()+ "\n";
              JOptionPane.showMessageDialog(this, "Vetor ordenado por Valor: \n" + aux);

        }
           
          }  // até aqui ele funciona. então resolvi colocar esse botão a mais mas não sei como  usar. quero que na hora que clicar dá a opçao das marcas de carro e coloca no campo.
            if(e.getSource()==jComboBox1)
            {
             jComboBox1.addItem("sllasfdsl");
              JComboBox cb = (JComboBox)e.getSource();
               Object modelo = cb.getSelectedItem();
            
               //  updateLabel(petName);


            }
   }



}

2 Respostas

davidhellfire

boa tarde !

olha sei usar o componente JComboBox da seguinte forma

1º- vc cria a caixa de seleção
“nome do JCB” = new javax.swing.JComboBox();

[color=red]
para executar os seguites passos vc terá que criar uma classe no projeto MapCB, para mapeamento do combo[/color]

2º - vc cria uma variavel privada do tipo MapCB

private MapCB variavel;

3º - variavel = new MapCB(con,“comando SQL”,JCBFornec,ProgNome,0);

qualquer dúvida estamos ai…

davidhellfire

cria uma classe com o nome [color=red]MapCB[/color] com esse codigo

package [color=red]“nomedoseupacote”;[color=red]

//package nomepacote;
/*

  • MapCB.java
  • Created on 18 de maio de 2010, 13:51
  • To change this template, choose Tools | Options and locate the template under
  • the Source Creation and Management node. Right-click the template and choose
  • Open. You can then make changes to the template in the Source Editor.
    */

/**
*

  • @author Usuario
    /
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.sql.
    ;
    import javax.swing.JComboBox;
    import javax.swing.JOptionPane;
//////////////////////////////////////////////////////////////////////////

public class MapCB {

private String sql;

private ArrayList dados;
public MapCB(Connection con, String sql, JComboBox combo, String ProgNome, int inicio) {
    combo.removeAllItems();
    try{
        Statement stmt;
        ResultSet rs;
        stmt = con.createStatement();
        rs = stmt.executeQuery(sql);
        dados = new ArrayList();
        if (inicio == 1)  //inseri essa linha para permitir combo iniciarem com branco 11/03
            dados.add(new Elemento(0,"")); 
        while(rs.next()){
            Elemento e = new Elemento(rs.getInt(1), rs.getString(2));
            dados.add(e);
        }
    }
    catch(SQLException e){
        JOptionPane.showMessageDialog(null,
                "Erro na conex&#65533;o./n Erro: " + e.getMessage(), ProgNome,
                JOptionPane.ERROR_MESSAGE);
    }
    carregarElementos(combo);
}
public void carregarElementos(JComboBox combo){
    Iterator i = dados.iterator();
    while(i.hasNext()){
        Elemento e = (Elemento) i.next();
        combo.addItem(e.getDescricao());
    }
    if(combo.getItemCount() > 0)
        combo.setSelectedIndex(0);
}
public int retornarCodigo(JComboBox combo){
    String descricao = combo.getSelectedItem().toString();
    Iterator i = dados.iterator();
    while(i.hasNext()){
        Elemento e = (Elemento) i.next();
        if(e.getDescricao().equalsIgnoreCase(descricao))
            return e.getCodigo();
    }
    return 0;
}        

public void posicionarElemento(JComboBox combo, int codigo){
    Iterator i = dados.iterator();
    String descricao = null;
    javax.swing.ComboBoxModel dlm = combo.getModel();
    while(i.hasNext()){
        Elemento e = (Elemento) i.next();
        if(e.getCodigo() == codigo){
            descricao = e.getDescricao();
            break;
        }    
    }
    
    for(int x=0; x<=combo.getItemCount()-1; x++)
       if(dlm.getElementAt(x).toString().equalsIgnoreCase(descricao))
          combo.setSelectedIndex(x);
    
}
}

class Elemento{

private int codigo;

private String descricao;
public Elemento(int codigo, String descricao){
    this.codigo = codigo;
    this.descricao = descricao;
}
public int getCodigo(){
    return codigo;
}
public String getDescricao(){
    return descricao;
}

}

Criado 18 de maio de 2010
Ultima resposta 18 de mai. de 2010
Respostas 2
Participantes 2