Preciso de ajuda - navegação de telas[Resolvido]

7 respostas
E

Primeira vez que posto alguma coisa, desculpa se tiver algum erro. Tenho que fazer um trabalho pra faculdade de um programa em java que simula uma rede de relacionamentos com interface gráfica. O programa tem três janelas, uma que é a de login, outra para gerenciar o programa q deve ser acessível apenas pelo gerente e uma para os usuários comuns. O problema é que na tela de login quando clica no botão ok ela abre um quadradinho no alto da tela e trava tudo. Minha dficuldade está em fazer a navegação de telas. Eu to usando o netbeans 6.7.1 para elaborar a interface. Agradecerei demais se alguem puder me ajudar.

essaé a parte que fecha a tela de login e abre a do gerente

for(Gerente verifica : gerente){
            if(verifica.getNome().equals(nome) && verifica.getSenha().equals(senha)){
                this.answerText.setText("Bem Vindo");
                
                
                Gerenteadmin p1 = new Gerenteadmin(this);
                this.setEnabled(false);
                p1.setVisible(true);

            }
            else
                this.answerText.setText("Mal vindo");

esse é o construtor do gerente

public Gerenteadmin(Panel i) {
        f1=i;
        f1.setEnabled(false);
    }

valeu aí s e alguem puder ajudar!

7 Respostas

P

tenta colocar no teu jframe

//vai redimencionar o jframe para caber os componentes
teuJframe.pack();

Allan_Barcelos

O cara fiz um projeto parecido, vou postar uma parte do código, fiz por varias telas, uma para login, outra para a conta, e outra para cada botão:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class FrameInicial extends JFrame{
	
	PanelInicial pi;
	
	public FrameInicial(){
		
		setTitle("Bem vindo ao Projeto Conta");
		this.add(pi = new PanelInicial(this));
		this.pack();
		this.setLocationRelativeTo(null);
		this.add(pi);
		this.setLayout(null);
		this.setContentPane(pi);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
		this.setResizable(false);
	}
	
	
class PanelInicial extends JPanel implements ActionListener{
	
	public PanelInicial(JFrame f){

		super(new BorderLayout());
		frame = f;
		
        novo = new JButton("Criar nova conta");
        novo.addActionListener(this);
        
        load = new JButton("Carregar conta existente");
        load.addActionListener(this);
        
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(novo);
        buttonPanel.add(load);
        
        add(buttonPanel, BorderLayout.PAGE_START);
        
		
	}
	
	public void actionPerformed(ActionEvent e){

		if(e.getSource() == novo){
			c = new Conta();
			this.setVisible(false);
			FrameLogin pl = new FrameLogin(c, nomeArquivo, false);
			this.fecha();
			
		}
		else if (e.getSource() == load) {
		 if (returnVal == JFileChooser.APPROVE_OPTION) {
               File file = fc.getSelectedFile();
               c = leObjeto(file);
               nomeArquivo = file.getAbsolutePath();
               this.setVisible(false);
               FrameLogin pl = new FrameLogin(c, nomeArquivo, estado);
               this.fecha();
               }
               else{
            	   return;
               }
           }
       }
	
	
	public void fecha(){
		frame.dispose();
	}
}
public static void main(String[] args){
	FrameInicial fi = new FrameInicial();
}
}

E uma parte do código da tela de login:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class FrameLogin extends FrameInicial{

	
	PanelLogin pl;
	
	public FrameLogin(Conta cof, String nomeAr, boolean e){
		setTitle("Tela de Login");
		this.add(pl = new PanelLogin(this, cof, nomeAr, e));
		this.pack();
		this.add(pl);
		this.setLocationRelativeTo(null);
		this.setLayout(null);
		this.setContentPane(pl);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
		this.setResizable(false);
		this.setSize(pl.getSize());
	}
	
public class PanelLogin extends PanelInicial{

	
	public PanelLogin(JFrame f, Conta cof, String nomeAr, boolean e){
		super(f);
		nomeArquivo = nomeAr;
		c = cof;
		frame = f;
		estado = e;
		
		tx1 = new JLabel("Digite o nome");
		tf = new JTextField("************"); 
        tf.addActionListener(this);
		
        pf1 = new JLabel("Digite a senha");
		pf = new JPasswordField("*********");     
        pf.addActionListener(this);
        
        ok = new JButton("Seguir"); 
        ok.addActionListener(this);
        
        inf = new JButton("Help");
        inf.addActionListener(this);
        
        JPanel buttonPanel2 = new JPanel();
        JPanel buttonPanel3 = new JPanel();
        JPanel buttonPanel4 = new JPanel();
        
           situacao = new JLabel("");
        
        buttonPanel2.setLayout(new GridLayout(3,0));
        buttonPanel3.setLayout(new GridLayout(3,0));
        buttonPanel4.setLayout(new GridLayout(1,3));
        
            buttonPanel4.add(situacao);
            buttonPanel2.add(tx1);
            buttonPanel2.add(tf);
	        buttonPanel3.add(pf1);
	        buttonPanel3.add(pf);
	        buttonPanel4.add(ok);

	        add(buttonPanel4, BorderLayout.PAGE_START);
	        add(buttonPanel2, BorderLayout.CENTER);
	        add(buttonPanel3, BorderLayout.PAGE_END);
        }   
	       
	
	public boolean validaLogin(String login, String senha){
		
		boolean usuario = false;
		boolean adm = false;
		
		if(c.getNome().equals(login) == true && c.getSenha().equals(senha)){
			usuario = true;
		}
		
			if(login.equals(c.getNomeAdm()) == true && senha.equals(c.getSenhaAdm()) == true){
				adm = true;
			}
				
			if(usuario == true | adm == true)
				return true;
			
			
			else
				return false;
		
	}


    
	public void actionPerformed(ActionEvent e) {
		String resp;
		boolean status;
		
		if(c != null)
		if(e.getSource() == ok){
			if(c.getNome() != null && c.getSenha() != null && count < 2){
				resp = new String(pf.getPassword());
				status = this.validaLogin(tf.getText(), resp);
				if(status == true){
				FramePrincipal fp = new FramePrincipal(c);
				this.setVisible(false); // Faz "desaparecer" essa janela
				this.fecha();
				}
				else if(status == false){
					JOptionPane.showMessageDialog(null, "Nome, ou senha Incorretos!", "Failed to Login!", JOptionPane.ERROR_MESSAGE);
					count++;
				}
					
			}
			
			else if(count >= 2){
				JOptionPane.showMessageDialog(null, "O programa vai ser encerrado! \n A sua conta sera travada", "Failed to Login!", JOptionPane.ERROR_MESSAGE);
				this.salvaDados();
			}
			
			else{
				c = new Conta();
				resp = new String(tf.getText());
				c.setNome(resp);
				resp = new String(pf.getPassword());
				c.setSenha(resp);
				status = this.validaLogin(tf.getText(), resp);
				if(status == true){
					this.setVisible(false);
					FramePrincipal fp = new FramePrincipal(c);
					this.fecha();
				}
			}
				
		}else if(e.getSource() == inf){
			FrameDesblo fd = new FrameDesblo();
			}
		

}
	
	public void fecha(){
		frame.dispose();
	}
	
	public void salvaDados(){}
}
}

Consegui fazer por essa lógica, um panel dentro de um frame, passando as informações como atributos para as outras classes.

E

Allan,
meu grande problema tá na hora de abrir a outra janela, pq ela abre só um quadradinho, que comando vc acha q eu teria q dar pra ela abrir normalmente? pq senão eu teria q recomeçar do zero pra entender o q vc fez… valeu de qualquer forma eu vou tentar entender aki!

Allan_Barcelos

olha cara, no botão “ok” da classe do login, tu deve, fazer o this.setVisible(false) e instanciar a outra janela ex:

FrameGerente fg = new FrameGerente();

Seria mais facil se fosse JFrame, pelos varios metodos e talz, até pode usar JPanel, mais acho mais facil com o JFrame e o JPanel como internalClass, de qualquer modo, coloca o código da janela que tem que abrir no botão “ok” se possivel, na sua outra janela deve ter o this.serVisible(true);

E

vou tentar aki…

E

Ow muito o brigado, realmente meu problema devia estar voltado para algo relacionado ao jpanel, eu refiz ele usando jframe e funcionou direitinho. Valeu!

Allan_Barcelos

Tranquilo…, coloca resolvido no titulo caso não tenha mais essa duvida :wink:

Criado 6 de junho de 2010
Ultima resposta 13 de jun. de 2010
Respostas 7
Participantes 3