Create data validation and page sequence

3

I'm starting in Java and want to make a screen where the person signs the login and the password, the system stores the data and then in a new window is asked to enter the user and password, I did the part of validation and registration of the data on the same page, since I do not dominate the JFrames .

How do I separate things, for example create a page and then close it and open a new one? I do not know where I can close the code and open a new one, for example.

Follow the current code, I'm working with Eclipse.

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 


public class Exemplo1 extends JFrame implements ActionListener{ 

JButton entrar; 
JTextField cxnome; 
JTextField cxsenha; 
JLabel rotulo; 

JTextField cxvarnome; //variavel de senha a ser inserida
JTextField cxvarsenha; //variavel de senha a ser inserida

public void actionPerformed(ActionEvent evento){ 
String nome, senha, suasenha, seunome; 
nome = cxnome.getText(); 
senha = cxsenha.getText(); 
seunome = cxvarnome.getText(); 
suasenha = cxvarsenha.getText(); 



//metodo da interface ActionListener 
//como o tipo String não é um tipo primitivo, e sim 
//um tipo referencial, sua comparação não pode ser == 
if (evento.getSource()== entrar && nome.equals(seunome)&& senha.equals(suasenha)){

    rotulo.setText("CORRETO");
    dispose();


}
else{
    rotulo.setText("FALHO");
}
}


public static void main(String[] args){ 
    //instanciando objeto 
    Exemplo1 janela = new Exemplo1(); 
    janela.setVisible(true); 
    janela.setTitle("login"); 
    janela.setSize(200,200); 
    janela.setLocation(400,300); 


    } 

//construtor 
public Exemplo1(){ 
//gride para os objetos 
getContentPane().setLayout(new GridLayout(4,1)); 

cxvarnome = new JTextField();//instanciando 
getContentPane().add(cxvarnome);//coloca... no grid 

cxvarsenha = new JTextField();//instanciando 
getContentPane().add(cxvarsenha);//coloca... no grid 

cxnome = new JTextField();//instanciando 
getContentPane().add(cxnome);//coloca... no grid 

cxsenha = new JTextField();//instanciando 
getContentPane().add(cxsenha);//coloc... no grid 


entrar = new JButton("OK");//instanciando 
getContentPane().add(entrar);//coloca... no grid 
entrar.addActionListener(this);//add evento ao clicar 

rotulo = new JLabel();//instanciando 
getContentPane().add(rotulo);//coloca... no grid 
rotulo.setOpaque(true);//tornando opaco 
rotulo.setBackground(Color.orange); 



} 

}
    
asked by anonymous 28.08.2014 / 15:09

1 answer

4

Use CardLayout that allows you to work with multiple JPanel in of Container . With this layout you can easily control the flow of the panels using methods to toggle them:

first(C)    // Alterna para o primeiro painel adicionado no container (C).
last(C)     // Alterna para o último painel inserido no container (C).
next(C)     // Muda para o painel seguinte em (C).
previous(C) // Muda para o painel anterior em (C).
show(C, N)  // Alterna para o painel com nome (N) dentro do container (C).

This would avoid creating an application with multiple JDialog and / or JFrame .

_

In your code you are inserting all components directly into JFrame . One improvement to make is to separate the two views (Registry and Login) you want into JPanel different.

// Painel de criação do usuário
JPanel registerView = new JPanel();

// Painel de login
JPanel loginView = new JPanel();

To avoid adding everything directly to JFrame , a "root" panel can be created where everything will happen inside it (and it will have CardLayout as layout).

/* 
 * É importante armazenar em uma variável para podermos controlar o fluxo
 * dentro do JPanel através dos métodos listados no início dessa resposta.
 */
CardLayout card = new CardLayout();

// JPanel onde serão inseridos os JPanels
JPanel rootPanel = new JPanel();
rootPanel.setLayout(card); // definindo o layout 

Finally, just add the registration and login panels within rootPanel . Here, the way to add is slightly different from the simple jframe.add(jpanel) , in addition to the component we want to add, we also need to pass a unique name so we can identify it.

//Inserindo os painéis de Registro e Login,
rootPanel.add(registerView, "register");
rootPanel.add(loginView, "login");

// Painel que será exibido primeiro
card.show(rootPanel, "register"); // mostrará o painel com nome "register"

Test code

//Window.java

import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public final class Window extends JFrame {

    public Window(String title){
        super(title);
        init();
    }

    // Inicializa os componentes
    public void init(){
        setSize(300,300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // Painel de criação do usuário
        JPanel registerView = new JPanel();
        registerView.setLayout(null);

        // Botão que avançará para o próximo painel.
        JButton btnNext = new JButton("Me Registrei! Próximo Painel");
        btnNext.setBounds(50, 100, 200, 35);
        registerView.add(btnNext);

        // Painel de login
        JPanel loginView = new JPanel();
        loginView.setLayout(null);

        JLabel lblLoginPanel = new JLabel("Esse é o painel de login");
        lblLoginPanel.setBounds(70, 100, 150, 35);
        loginView.add(lblLoginPanel);

        CardLayout card = new CardLayout();

        // JPanel onde serão inseridos os JPanels
        JPanel rootPanel = new JPanel();
        rootPanel.setLayout(card); // definindo o layout
        getContentPane().add(rootPanel);

        // Inserindo os painéis de Registro e Login,
        rootPanel.add(registerView, "register");
        rootPanel.add(loginView, "login");

        card.show(rootPanel, "register"); // mostrará o painel de registro

        // Quando clicado...
        btnNext.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                card.next(rootPanel); // mostra o próximo JPanel dentro do container
            }
        });
    }
}

-

//Main.java
public class Main {
   public static void main(String[] args) throws IOException {
      new Window("StackOverflow").setVisible(true);
   }
}

Result

In your code, you can have the panel advanced when the user clicks, for example, a log completion button after filling in the required fields. The issue of validating the user is apparently already implemented in your code.

    
17.12.2014 / 09:24