Ajuda com combobox

3 respostas
L

Fala Galera sou novo no forum e gostei do que achei aqui.Sou desenvolvedor web ( PHP) mas estou cursando Ciencias da Computação…e estou com um problema.
Dei uma pesquisada aqui no forum e não achei nada que pudesse me ajudar ( ainda) e nem na net , mas continuo pesquisando.

O problema é o seguinte:
Criei uma interface que contém uma combobox e um JtextField .
Essa inteface carrega um arquivo de texto que contem uma lista de multas…pontos e etc …
Bom consegui fazer que o combobox carregue e mostre os codigos mas agora vem a parte que me enrolei …com um JOptionPane eu mostro cada um deles , mas já pensou vc mostrar uns 500 codigos dessa forma? então tenho que selecionar um codigo qualquer e este mostrar a sua descrição no JTextField…
Alguem consegue me ajudar? Desde já agradeço …

Ta aí o codigo :

package pctInterfacegrafica;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

import javax.swing.JOptionPane;

public class Multas extends javax.swing.JFrame {

public Multas() {
    initComponents();
}


@SuppressWarnings("unchecked")-----aqui o codigo ta escondido 
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    cmb_codigo = new javax.swing.JComboBox();
    txtcaixa = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowOpened(java.awt.event.WindowEvent evt) {
            formWindowOpened(evt);
        }
    });
    getContentPane().setLayout(null);

    cmb_codigo.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cmb_codigoActionPerformed(evt);
        }
    });
    getContentPane().add(cmb_codigo);
    cmb_codigo.setBounds(40, 30, 110, 20);

    txtcaixa.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N
    getContentPane().add(txtcaixa);
    txtcaixa.setBounds(30, 80, 310, 120);

    setBounds(0, 0, 416, 338);
}// </editor-fold>                        

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
    try{
    BufferedReader input = new BufferedReader(
            new FileReader(new File("C:/Users/Lau/Documents/multas2.txt")));
            
                String line=null;
                while((line=input.readLine())!=null){
                    String cod =line.substring(0,6);
                    String x[]=line.split("\t");
                    //JOptionPane.showMessageDialog(null,x[0].toString());
                    //JOptionPane.showMessageDialog(null,x[1]);
                    //JOptionPane.showMessageDialog(null,x[2]);
                    //JOptionPane.showMessageDialog(null,x[3]);
                    //JOptionPane.showMessageDialog(null,x[4]);
                    //JOptionPane.showMessageDialog(null,x[5]);
                    //JOptionPane.showMessageDialog(null,x[6]);
                    //JOptionPane.showMessageDialog(null,x[7]);
                    cmb_codigo.addItem(x[0]);
aqui ta comentado pra não abrir um monte de JOptionPanesei que o caminho esta por aqui para poder pegar os textos 

}

}

catch(IOException ex){

ex.printStackTrace();

}
}                                 

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

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Multas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Multas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Multas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Multas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Multas().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JComboBox cmb_codigo;
private javax.swing.JTextField txtcaixa;
// End of variables declaration

}

3 Respostas

YoungCaesar

Olá!

Antes de mais nada, ao postar no fórum use as tags [ code ] [/ code] para códigos, isso facilita muito a leitura.

Você pode mudar sua variável x para global e adicionar o seguinte código no método cmb_codigoActionPerformed

txtcaixa.setText(x[cmb_codigo.getSelectedIndex()]);

Valeu!

adsadilson

Bom se vc carrega o seu Jcombobox com List de objeto é só usar esse metodo aqui

private void selectComboox() {
        jcombobox.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                txtcaixa.setText = listaItens.get(jcombobox.getSelectedIndex());

            }
        });

    }
e para chamar esse metodo no construtor da classe selectComboox();
L

[b]Antes de mais nada, ao postar no fórum use as tags [ code ] [/ code] para códigos, isso facilita muito a leitura.

Você pode mudar sua variável x para global e adicionar o seguinte código no método cmb_codigoActionPerformed [/b]

Desculpe foi a primeira postagem e nem me atentei a esse erro…não esqueço mais.

Bom vamos lá …sou meio iniciante no Java e algumas coisas ainda me perco.

Criei o que você disse …o seu codigo e o mesmo me pediu um array , então criei a array,

public String x[]; e o seu codigo ficou livre de erros , mas quando executei o arquivo a lista de multas sumiu.

Ou seja a lista de multas que esta no arquivo de texto nem os seus codigos apareceram para mim.

Entendeu ?

No arquivo texto esta um monte de codigos de multas onde ela tem um numero e sua descrição, no select tem o numero correspondente e vou escolher o codigo da multa e no JTextField tem que aparecer a descrição da mesma.

Olha aí o codigo como ficou depois da sua dica:

package pctInterfacegrafica;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JOptionPane;

/**
 *
 * @author Lau
 */
public class Multas extends javax.swing.JFrame {
    public String x[];
    /**
     * Creates new form Multas
     */
    public Multas() {
        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() {

        cmb_codigo = new javax.swing.JComboBox();
        txtcaixa = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });
        getContentPane().setLayout(null);

        cmb_codigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmb_codigoActionPerformed(evt);
            }
        });
        getContentPane().add(cmb_codigo);
        cmb_codigo.setBounds(40, 30, 110, 20);

        txtcaixa.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N
        getContentPane().add(txtcaixa);
        txtcaixa.setBounds(30, 80, 310, 120);

        setBounds(0, 0, 416, 338);
    }// </editor-fold>                        

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
        try{
        BufferedReader input = new BufferedReader(
                new FileReader(new File("C:/Users/Lau/Documents/multas2.txt")));
                
                    String line=null;
                    while((line=input.readLine())!=null){
                        String cod =line.substring(0,6);
                        String x[]=line.split("\t");
                        //JOptionPane.showMessageDialog(null,x[0].toString());
                        //JOptionPane.showMessageDialog(null,x[1]);
                        //JOptionPane.showMessageDialog(null,x[2]);
                        //JOptionPane.showMessageDialog(null,x[3]);
                        //JOptionPane.showMessageDialog(null,x[4]);
                        //JOptionPane.showMessageDialog(null,x[5]);
                        //JOptionPane.showMessageDialog(null,x[6]);
                        //JOptionPane.showMessageDialog(null,x[7]);
                        cmb_codigo.addItem(x[0]);
                      
                    }                
                 }
                 catch(IOException ex){
                ex.printStackTrace();
                 }  

    }                                 

    private void cmb_codigoActionPerformed(java.awt.event.ActionEvent evt) {                                           
        txtcaixa.setText(x[cmb_codigo.getSelectedIndex()]); 
    }                                          

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Multas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Multas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Multas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Multas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Multas().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JComboBox cmb_codigo;
    private javax.swing.JTextField txtcaixa;
    // End of variables declaration                   
}

Quanto ao metodo ele reclama a criação das variaveis setText e deixa o listaItens sublinhado de vermelho …e nem imagino que erro é esse …

Olha aí o codigo depois do metodo implementado ( e nem sei onde eu chamo esse metodo)

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

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JOptionPane;

/**
 *
 * @author Lau
 */
public class Multas extends javax.swing.JFrame {

    /**
     * Creates new form Multas
     */
    public Multas() {
        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() {

        cmb_codigo = new javax.swing.JComboBox();
        txtcaixa = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });
        getContentPane().setLayout(null);

        cmb_codigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmb_codigoActionPerformed(evt);
            }
        });
        getContentPane().add(cmb_codigo);
        cmb_codigo.setBounds(40, 30, 110, 20);

        txtcaixa.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N
        getContentPane().add(txtcaixa);
        txtcaixa.setBounds(30, 80, 310, 120);

        setBounds(0, 0, 416, 338);
    }// </editor-fold>                        

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
        try{
        BufferedReader input = new BufferedReader(
                new FileReader(new File("C:/Users/Lau/Documents/multas2.txt")));
                
                    String line=null;
                    while((line=input.readLine())!=null){
                        String cod =line.substring(0,6);
                        String x[]=line.split("\t");
                        //JOptionPane.showMessageDialog(null,x[0].toString());
                        //JOptionPane.showMessageDialog(null,x[1]);
                        //JOptionPane.showMessageDialog(null,x[2]);
                        //JOptionPane.showMessageDialog(null,x[3]);
                        //JOptionPane.showMessageDialog(null,x[4]);
                        //JOptionPane.showMessageDialog(null,x[5]);
                        //JOptionPane.showMessageDialog(null,x[6]);
                        //JOptionPane.showMessageDialog(null,x[7]);
                        cmb_codigo.addItem(x[0]);
                      
                    }                
                 }
                 catch(IOException ex){
                ex.printStackTrace();
                 }  

    }                                 

    private void cmb_codigoActionPerformed(java.awt.event.ActionEvent evt) {                                           
        
    }                                          
        private void selectComboox() {  
           cmb_codigo.addActionListener(new ActionListener() {  
      
               @Override  
               public void actionPerformed(ActionEvent arg0) {  
                   txtcaixa.[u]setTex[/u]t = [u]listaItens[/u].get(cmb_codigo.getSelectedIndex());  
      
               }  
           });  
      
       }  
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Multas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Multas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Multas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Multas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Multas().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JComboBox cmb_codigo;
    private javax.swing.JTextField txtcaixa;
    // End of variables declaration                   
}
Criado 22 de abril de 2013
Ultima resposta 22 de abr. de 2013
Respostas 3
Participantes 3