Alguem alem do Daitel sabe fazer isso?

9 respostas
F

galera to com problema no evento do JComobBox por incrivel que pareça ja vou pra quase 3 semana postando em variso foruns e ninguem resolve o problema,
oq eu quero é simplesmente selecionar uma opçao no JComboBox e em seguida que seja escrito na console o nome da opção que eu escolhi por exemplo
selecionei cachorro no jcombobox em seguida deve escrever na console cachorro so isso !!!
será que alguem no mundo sabe fazer isso??? bom segue abaixo meu codigo ta dando um erro se alguem conseguir consertar eu agradeço
mais uma vez obrigado a todos

import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class SorteGrande extends JFrame
{

	private final JButton   sorteio,sair;
	private final JLabel    label;
	private final JPanel    painelnorte,painelcenter,painelsul;	
	private final JComboBox combo;
	public SorteGrande()
	{
		super ("Sorte Grande v.01")	;
		setLayout(new BorderLayout());
				
		//Tratamento botão sortear com evento 
		sorteio = new JButton("Sortear");
		
		//tratamento JComboBox
	
		String[] vetor={"Dupla Sena","Loto Fácil","Loto      Mania","Mega Sena","Quina"};
		
	    JComboBox escolha= new JComboBox(vetor);
		
                    //so a linha abaixo que ta dando pau
                      escolha.addActionListener(this);	
	
		//Tratamento botão sair com evento
		sair    = new JButton("Sair");
		sair exit =new sair();
		sair.addActionListener(exit);
		
			
		//tramento  Painel
		painelcenter =new JPanel();
		painelnorte  =new JPanel();
		painelsul    =new JPanel();
		
		//Tratamento do label
		label   =new JLabel("Escolha a opção para gerar o palpite");
		
		//Adicionando paineis
		add(painelnorte,  BorderLayout.NORTH);
		add(painelcenter, BorderLayout.CENTER);
		add(painelsul,    BorderLayout.SOUTH);
		
		//painel nort
		painelnorte.  add(label);
		painelcenter.  add(escolha);
	
		//painel sul
		painelsul.    add(sorteio);
		painelsul.    add(sair);
		pack();
		
		
	   setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}

    //inicio tratamento evento jcombobox
    public void actionPerformed(ActionEvent e){
    
    JComboBox cb=(JComboBox)e.getSource();
    String escolha=(String)cb.getSelectedItem();	
   	System.out.println(escolha);
    }
     
    
    //fim tratamento evento jcombobox
    
    
    
	public class sair implements ActionListener
{
	public void actionPerformed(ActionEvent e)
	{	
		String opcoes[] = {"Sim","Não"};
		int     opc     = JOptionPane.showOptionDialog(null,"Confirma o encerramento?","Confirmação",JOptionPane.DEFAULT_OPTION,JOptionPane.QUESTION_MESSAGE,null,opcoes,opcoes[1]);
		//
		if ( opc == 0 )
			System.exit(0);
	}
	
}
	


	public static void main(String args[])
	{
	
	SorteGrande ref = new SorteGrande();
	
	}	

	
}

9 Respostas

Ratao

Mude uma parte do seu código conforme abaixo e veja se lhe atende:

final JComboBox escolha= new JComboBox(vetor); 
            
          //so a linha abaixo que tava dando pau rsrsrsrs...
              escolha.addActionListener(new ActionListener(){
		  public void actionPerformed(ActionEvent evt) {
			System.out.println(escolha.getSelectedItem().toString());
		}                    	   
            });
Giulliano

Acho q muita gente além do deitel sabe fazer isso…se ninguém te ajudou ainda é pq é hora de vc parar para resolver sozinho…

Digo isso pq às vezes é mais fácil esperar que os outros percam tempo arrumando seu programa do que vc parar para pensar, afinal estamos numa área de exatas…desculpe se fui meio grosso mas é isso ae… [/]'s

Giulliano

Acho q muita gente além do deitel sabe fazer isso…se ninguém te ajudou ainda é pq é hora de vc parar para resolver sozinho…

Digo isso pq às vezes é mais fácil esperar que os outros percam tempo arrumando seu programa do que vc parar para pensar, afinal estamos numa área de exatas…desculpe se fui meio grosso mas é isso ae… [/]'s

kaique

Cara, pelo que eu estou vendo, você está querendo que a classe SorteGrande seja responsável por “escutar” os eventos da JComboBox do seu programa. No caso está quase certo, pois você realmente escreveu o método responsável por tratar os eventos (actionPerformed()), mas você esqueceu de declarar que a classe SorteGrande era uma tratadora de eventos. Para fazer isso, você precisa fazer com que ela implemente ActionListener. O problema de compilação que ocorre é que você está tentando passar para o método addActionListener() uma classe que não é do tipo ActionListener…

[]'s.

F

Complementando o que o kaique falou vc precisa mudar:
public class Teste extends JFrame
para
public class Teste extends JFrame implements ActionListener

e retirar a linha: private final JComboBox combo;
não é utilizada no código e a compilação não passou

raphael_adrien

Opa tudo bom, cara peguei seu codigo alterei 2 linhas ele funcionou.

public class SorteGrande extends JFrame implements ActionListener

Como ja tinha sido dito, sua classe sorte grande deve implementar ActionListener.

Há você deve alterar a linha.

para

Você declarou ela como final, ou seja a referencia desse objeto será a ultima certo,e vc não está inicializando essa referencia o compilador ira reclamar que ela precisa ser inicializada.

Bons Códigos.

Filipe_Portes

Toma ai garoto,

Ta Prontinho...

/**
 *
 * @author  Filipe Portes
 */
public class NovoJFrame extends javax.swing.JFrame {
    
   
    public NovoJFrame() {
        initComponents();
        setLocationRelativeTo(null);
    }
    
   
    // <editor-fold defaultstate="collapsed" desc=" Código Gerado ">                          
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        boxMes = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtMes = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("ComboBox");
        setResizable(false);
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Usando ComboBox"));
        boxMes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--Selecione a op\u00e7\u00e3o--", "Janeiro", "Fevereiro", "Mar\u00e7o", "Abril", "Maio", "Junho", "Junlho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" }));
        boxMes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boxMesActionPerformed(evt);
            }
        });

        jLabel1.setText("Meses:");

        jLabel2.setText("Voc\u00ea selecionou:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(boxMes, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtMes, javax.swing.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(boxMes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(32, 32, 32)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtMes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(29, Short.MAX_VALUE))
        );

        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.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pack();
    }// </editor-fold>                        

    private void boxMesActionPerformed(java.awt.event.ActionEvent evt) {                                       

       String text = boxMes.getSelectedItem().toString();
       txtMes.setText(text);
       txtMes.setForeground(Color.BLUE);
       System.err.println(text);
        
    }                                      
    
    
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NovoJFrame().setVisible(true);
            }
        });
    }
    
    // Declaração de variáveis - não modifique                     
    private javax.swing.JComboBox boxMes;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField txtMes;
    // Fim da declaração de variáveis                   
    
}

Fiz no netbeans pra ir mais rapido, mas se quiser faço na unha e mando pra vc!!!!!!!!!

TEstei e ta Funcionando, Espero que Possa te Ajudar!!!!!!!!1

A
Ratao:
Mude uma parte do seu código conforme abaixo e veja se lhe atende:
final JComboBox escolha= new JComboBox(vetor); 
            
          //so a linha abaixo que tava dando pau rsrsrsrs...
              escolha.addActionListener(new ActionListener(){
		  public void actionPerformed(ActionEvent evt) {
			System.out.println(escolha.getSelectedItem().toString());
		}                    	   
            });

Particularmente eu prefiro essa solução implementada pelo ratao...
Fazer uma JFrame ser ActionListener implementando um metodo ActionPerformed acho um tanto feio... ou vc pode fazer uma listener como classe interna como vc fez com a classe 'sair'
Ah e não esqueca do padrão de nomenclaturas... nomes de classes devem começar com letras maiusculas...

F

Giulliano
amigo não estou querendo nada de graça,mto menos estou com pregruiça de tentar sozinho até pq este programinha banal bobo e ridiculo que eu to apanhando pra fazer não serve para nada a não ser para aprender.
a importancia disto pra min é simplesmente entender, to pedindo ajuda pq tem algum tempo que to tentando e não consegui fazer pode ser facil mas eu não consegui e não tenho vergonha de dizer QUE NÂO CONSEGUI FAZER UMA COISA SIMPLES desta, afinal ninguem nasce sabendo se eu tivesse afim deste programa pronto e tivesse com preguiça pagaria alguem pra fazer!!!
so pedi alguem pra resolver, para min poder ver onde estava o meu erro para tentar acertar!!!
Afinal não é vergonha não saber, vergonha é responder uma duvida de programação com esporro que não leva ninguem a lugar nenhum

Ainda agradeço aos amigos ai que souberam ou não responder minha pergunta e deixo claro que qualquer duvida que eu postar aqui não é meramente preguiça é simplesmente pq não consegui sozinho!!!
afinal eu escolhi tentar aprender Java e so vou consegui com meu esforço !!!
infelizmente ainda vou precisar muito incomodar quem tiver boa vontade pra me ajudar.
valew

Criado 13 de setembro de 2007
Ultima resposta 13 de set. de 2007
Respostas 9
Participantes 8