JButton para abrir uma nova Classe

2 respostas
JaqueTurbiani

Olá, sei que vcs já ajudaram muitas pessoas, mas mesmo pesquisando muito não estou conseguindo fazer com que o Botão abra uma nova tela.
Por favor, me ajudem!!!

O sistema funciona(deveria funcionar) ao clicar no botão cadastro, buscar a tela cadastro. E no botão entrar, após digitar os dados da tela principal, buscar a tela de consulta.
Vou colocar o código para ver se podem me ajudar.

Tela Principal (Login)

package gui;

import java.*;

import javax.swing.JButton;

import javax.swing.JComponent;

import javax.swing.JFrame;

import javax.swing.JPanel;
import java.awt.Color;

import java.awt.Component;

import java.awt.Container;

import java.awt.Window;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.FlowLayout;

import javax.swing.*;
import javax.swing.border.EmptyBorder;

@SuppressWarnings({ unused })

public class Login extends JFrame implements ActionListener{

/**

*

*/

private static final long serialVersionUID = 1L;
static int Conta;
char Senha;

Container cp = getContentPane(); //Container  
	/*Declaração de Variável*/
JLabel LbConta;
JLabel LbSenha; 
JLabel LbTipo;
JTextField TxConta;
JTextField TxSenha;  
JComboBox CmTipo;  

JButton BtEntrar;
JButton BtSair;  

static JButton BtCadastro;


@SuppressWarnings({ })
public Login(){  
    setTitle("Login");  
    setSize(430, 270);  
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
         
    LbConta = new JLabel("Conta:");  
    TxConta = new JTextField("");
    LbSenha = new JLabel("Senha:");
    TxSenha = new JTextField("");
    LbTipo = new JLabel("Tipo:");        
    CmTipo  = new JComboBox();  
    BtCadastro = new JButton("Cadastrar Nova Conta");  
    BtEntrar = new JButton("Entrar");  
    BtSair = new JButton("Sair");  
         
    
    
                        
    BtCadastro.addActionListener(    
       new ActionListener(){    
          public void actionPerformed(ActionEvent evento){    
                 JFrame Cadastro = new JFrame();  
                 Cadastro.setVisible(true); 
                                      
          }    
       }    
    );  
   	
     
           
    BtEntrar.addActionListener(    
       new ActionListener(){    
          public void actionPerformed(ActionEvent event){   
        	  	JFrame Consulta = new JFrame(); 
                Consulta.setVisible(true); 
                
                 
          }  
       }    
    ); 
	
	

  
    cp.add(BtSair);   


    BtSair.addActionListener(new ActionListener() {    
        @Override    
        public void actionPerformed(ActionEvent ev) {    
           System.exit(0);    
        }    
    });   
      
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
       
    
    
    
    CmTipo.setModel(new javax.swing.DefaultComboBoxModel (new String[]{
    		"Tipo de Conta","Corrente","Poupança"
    }));
   
    getContentPane().setLayout(null);
    
    getContentPane().add(LbConta);  
    getContentPane().add(TxConta); 
    getContentPane().add(LbSenha);
    getContentPane().add(TxSenha);
    getContentPane().add(LbTipo);  
    getContentPane().add(CmTipo);  
    getContentPane().add(BtCadastro);  
    getContentPane().add(BtEntrar);  
    getContentPane().add(BtSair); 
    
    LbConta.setBounds(130, 23, 100, 15);  
    TxConta.setBounds(175, 20, 80, 25); 
    LbSenha.setBounds(130, 63, 120, 15);  
    TxSenha.setBounds(175, 60, 100, 25);
    LbTipo.setBounds(130, 103,300, 15);  
    CmTipo.setBounds(175, 100,120, 25); 
    
    BtCadastro.setBounds(20,170,180, 30);  
    BtEntrar.setBounds(210,170,80, 30);  
    BtSair.setBounds(300,170,80, 30);  
    
}


public static void main(String args[]){  
        new Login().setVisible(true);  
    
  }

@Override
public void actionPerformed(ActionEvent e) {
	
	
}
  
	 
}

Tela Cadastro

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Scanner;
import javax.swing.AbstractButton;

import javax.swing.ButtonGroup;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JRadioButton;

import javax.swing.JTextField;
public class Cadastro extends JFrame implements ActionListener{

/**

*

*/

private static final long serialVersionUID = 1L;
JLabel LbNumero;
    JLabel LbNome;
    JLabel LbSaldo;
    JLabel LbSenha;
    JLabel LbCorrente;
    JLabel LbPoupanca;
    JTextField TxNumero;
    JTextField TxNome;
    JTextField TxSaldo;
    JTextField TxSenha;	    
    static JButton BtCadastro;
    JButton BtSair;
    JButton BtConsulta;

    private JRadioButton[] RadioButton = new JRadioButton[2];
    private ButtonGroup Radio_Group = new ButtonGroup();
    private JLabel Label_Pergunta = new JLabel();
    
    public Cadastro(){
    	
    	RadioButton[0] = new JRadioButton("Corrente");
	    RadioButton[1] = new JRadioButton("Poupança",true);
	    
	    Label_Pergunta.setText("Escolha o tipo da Conta");
	    
	    this.setLayout(new GridLayout(3,1));
	    this.add(Label_Pergunta);
	    
	    for (int i = 0; i<RadioButton.length; i++){
	        Radio_Group.add(RadioButton[i]);
	        this.add(RadioButton[i]);
	    }
	    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    this.setSize(325, 200);
	    this.setResizable(false);
	    this.setLocationRelativeTo(null);
	    this.setVisible(true);
	    
    }
    
    public static void main1(String[] args){
        new Cadastro().setVisible(true);
    }
     
       
	private int Numero1;
	private float Saldo1;
	private String Nome1;
	private String Senha1;
	
	public Pessoa pa[]=new Pessoa[10];
	Scanner s = new Scanner(System.in);
	
		int contador=0;
	
    public Cadastro(AbstractButton b1, JRadioButton b2){  
        setTitle("Cadastro");  
        setSize(450, 350);  
        /*setDefaultCloseOperation(DISPOSE_ON_CLOSE);*/
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane() .setLayout(null);
        
        
        LbNumero = new JLabel("Número");
        TxNumero = new JTextField(""); 
        LbNome   = new JLabel("Nome");
        TxNome   = new JTextField(""); 
        LbSaldo  = new JLabel("Saldo Inicial");
        TxSaldo  = new JTextField(""); 
        LbSenha  = new JLabel("Senha");
        TxSenha  = new JTextField(""); 
        LbCorrente = new JLabel("Corrente");
        LbPoupanca = new JLabel("Poupança");
        BtCadastro = new JButton("Cadastrar");  
        BtSair     = new JButton("Sair");  
        
        BtConsulta = new JButton("Consulta");
        
        /*getContentPane().setLayout(null);*/  
        
        getContentPane().add(LbNumero);  
        getContentPane().add(LbNome);
        getContentPane().add(LbSaldo);  
        getContentPane().add(LbSenha);
        getContentPane().add(LbCorrente);
        getContentPane().add(LbPoupanca);
        getContentPane().add(TxNumero);  
        getContentPane().add(TxNome);  
        getContentPane().add(TxSaldo);          
        getContentPane().add(TxSenha);  
        getContentPane().add(BtCadastro);  
        getContentPane().add(BtSair);  
        
        getContentPane() .add(BtConsulta);
        
        
        LbNumero.setBounds(20, 20, 100, 15);  
        TxNumero.setBounds(20, 40, 80, 25);    
        LbNome.setBounds(20, 70, 100, 15);  
        TxNome.setBounds(20, 90, 350, 25);  
        LbSaldo.setBounds(20, 120,300, 15);  
        TxSaldo.setBounds(20, 140,100, 25);    
        LbSenha.setBounds(150,120,100, 15);  
        TxSenha.setBounds(150,140,100, 25);  
        LbCorrente.setBounds(20,180,150, 15);  
        LbPoupanca.setBounds(120,180,150, 15);
  
        BtCadastro.setBounds(20,240,180, 30);  
        BtSair.setBounds(300,240,80, 30); 
        
        /*BtConsulta.setBounds(420,250,120,20);*/
       	             
	    TxNumero.addActionListener (this);
        TxNome.addActionListener (this);
	    TxSaldo.addActionListener (this);
	    TxSenha.addActionListener (this);
	   
	   
	    JPanel panel = new JPanel();  
        ButtonGroup bg = new ButtonGroup();  
        b1 = new JRadioButton("Corrente");  
        bg.add(b1);  
        panel.add(b1);  
        b2 = new JRadioButton("Poupança");  
        bg.add(b2);  
        panel.add(b2); 





    
	    BtCadastro.addActionListener(this);
	    /*BtConsulta.addActionListener(this);*/
	    
	    
	    BtSair.addActionListener( new ActionListener(){  
	         public void actionPerformed( ActionEvent event ){  
	            setVisible( false );  
	         }  
	      }); 
	  
        	        
    }   
    
	public static void main(String args [])
	{
	Cadastro obj = new Cadastro(BtCadastro, null);
	obj.setVisible(true);
			  

    
                
	}
	
	
	
	public void actionPerformed(ActionEvent acao)
	{ 
	if(acao.getSource()==BtCadastro)
	{
		
		Pessoa p= new Pessoa();


		p .setLbNumero(TxNumero.getText());
		p .setNome(TxNome.getText());
		p .setLbSaldo(TxSaldo.getText());
		p .setLbSenha(TxSenha.getText());

		if(contador==0)
		{
		pa[0]=p;
		contador++;
		}
		else
		{
		pa[contador]=p;
		contador++;
		}
		
		JOptionPane.showMessageDialog(null,"Cadastro Efetuado com Sucesso!");
		}
		
	
			
	if(acao.getSource()==BtConsulta)
	{

	for(int i=0;i<contador;i++)
	{

	JOptionPane.showMessageDialog(null,"Dados"+
	"\nNumero: "+pa[i].getTxNumero()+
	"\nNome: "+pa[i].getTxNome()+ 
	"\nSaldo: "+pa[i].getTxSaldo()+
	"\nSenha: "+pa[i].getTxSenha());
}
	}
		}

	
	protected class Pessoa

	{

		public void setLbNumero(String text) {
					
		}

		public String getTxNumero() {
			
			return null;
		}

		public String getTxSenha() {
			
			return null;
		}

		public String getTxSaldo() {
			
			return null;
		}

		public String getTxNome() {
			
			return null;
		}

		public String getLbSenha() {
		
			return null;
		}

		public String getLbNome() {
			
			return null;
		}

		public String getLbSaldo() {
		
			return null;
		}

		public void setLbSaldo(String text) {
			
			
		}

		public void setLbSenha(String text) {
			
			
		}

		public void setNome(String text) {
		
			
		}
	
		
			}
	@SuppressWarnings("unused")
	private String getNumero() {
	
		return null;
	}

	protected class Pessoa1

	{
		int Numero1;
		String Nome1;
		String Senha1;
		float Saldo1;
		
				
	}
		
		void Pessoa(int Numero1,String Nome1, float Saldo1, String Senha1)
		{
			
		this.Numero1=Numero1;
		this.Nome1=Nome1;
		this.Saldo1=Saldo1;
		this.Senha1=Senha1;
		
		}
	
	public void setTxNumero(int Numero1){
		this.Numero1=Numero1;
	}
	public int getTxNumero(){
		return Numero1;
	}
	
	public void setTxNome(String Nome1) {
		this.Nome1=Nome1;
	}
	public String getTxNome(){
		return Nome1;
	}
	
	public void setTxSaldo(float Saldo1){
		this.Saldo1=Saldo1;
	}
	public float getTxSaldo(){
		return Saldo1;
	}
	
	public void setTxSenha(String Senha1) {
		this.Senha1=Senha1;
	}
	public String getTxSenha(){
		return Senha1;
	}

	public void setRadioButton(JRadioButton[] radioButton) {
		RadioButton = radioButton;
	}

	public JRadioButton[] getRadioButton() {
		return RadioButton;
	}

	public void setRadio_Group(ButtonGroup radio_Group) {
		Radio_Group = radio_Group;
	}

	public ButtonGroup getRadio_Group() {
		return Radio_Group;
	}

	public void setLabel_Pergunta(JLabel label_Pergunta) {
		Label_Pergunta = label_Pergunta;
	}

	public JLabel getLabel_Pergunta() {
		return Label_Pergunta;
	}

}

Tela Consulta

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class Consulta extends JFrame {

/**

*

*/

private static final long serialVersionUID = 1L;
JButton BtAtualizacao;
JButton BtSaque;
JButton BtDeposito;
JButton BtSair;

public Consulta(){  
    setTitle("Consulta");  
    setSize(530, 350);  
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    BtAtualizacao = new JButton("Atualização Monetária");  
    BtSaque = new JButton("Saque");  
    BtDeposito = new JButton("Depósito");
    BtSair = new JButton("Sair");
    
    getContentPane().setLayout(null);
    
    getContentPane().add(BtAtualizacao);  
    getContentPane().add(BtSaque);
    getContentPane().add(BtDeposito);
    getContentPane().add(BtSair); 
    
    BtAtualizacao.setBounds(20,240,180, 30);  
    BtSaque.setBounds(210,240,80, 30);
    BtDeposito.setBounds(300,240,100, 30);
    BtSair.setBounds(410,240,80, 30);  
    
    BtSair.addActionListener( new ActionListener(){  
         public void actionPerformed( ActionEvent event ){  
            setVisible( false );  
         }  
      }); 
    
}

  public static void main(String args[]){  
        new Consulta().setVisible(true);  
    }

}

Agradeço desde já.

2 Respostas

E

Bom,

um bom começo é vc tentar rodar seus frames separados, ver se cada frame está abrindo corretamente. Se teus frames estiverem aparecendo, então se vc chamá-los pelos botões, eles vão abrir conforme o click nos seus listeners.
Ao clicar nos botões é lançado alguma exception no console?

Coloque teu código entre as tags code para facilitar a visualização.
Siga os padrões para declarações de variáveis e atributos.

Use

JLabel lbConta;

em vez de

JLabel LbConta;
JaqueTurbiani

Eles estão funcionando.
Mas eu consegui resolver.

Obrigada!!!

Agora eu só não estou conseguindo adicionar um JRadioButton. Mas acho que esse seria um outro tópico.

Criado 10 de dezembro de 2012
Ultima resposta 10 de dez. de 2012
Respostas 2
Participantes 2