Create data validation and page sequencing

Asked

Viewed 727 times

3

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

How do I separate things, create, for example, a page and then close and open a new one? I don’t 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); 



} 

}
  • 2

    I don’t quite understand your question, but I think you could take a look at this question here: Toggle Jpanels within a single Jframe, maybe it helps (or maybe it doesn’t).

1 answer

4

Utilize Cardlayout that allows working with several JPanel within a Container. With this layout you can easily control the flow of panels using methods to change 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. An improvement to be made is to separate the two views (Registration and Login) you want in 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, can be created a "root" panel where everything will happen inside it (and it will have the 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 inside the 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);
   }
}

Upshot

inserir a descrição da imagem aqui inserir a descrição da imagem aqui

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.