How to close one screen after opening another?

Asked

Viewed 909 times

2

I’m having trouble closing screen, I’m programming in eclipse.

When running, the program opens and the Login window appears, when the user enters the correct code and password, a message appears to let you know that you have access, and then a second window must be opened. So far so good, but I’m having trouble closing only the Login window when the second window opens.

This is the login screen code.

package teste;

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

public class Login extends JFrame implements ActionListener {

    private JPanel jPanel, jp1, jp2, jp3;
    private JLabel lbSenha, lbCod;
    private JTextField jtfSenha, jtfCod;
    private JButton jbLogar, jbSair;
    private static TesteCon tc;
    private String janStat;

    Login(){
        jPanel = new JPanel(new BorderLayout());
        jp1 = new JPanel();
        jp2 = new JPanel();
        jp3 = new JPanel();

        lbSenha = new JLabel("Senha:");
        lbCod = new JLabel ("Codigo:");

        jtfSenha = new JTextField(10);
        jtfCod = new JTextField(10);

        jbLogar = new JButton("Logar");
        jbLogar.addActionListener(this);
        jbSair = new JButton("Sair");
        jbSair.addActionListener(this);

        jp1.add(lbCod);
        jp1.add(jtfCod);
        jp2.add(lbSenha);
        jp2.add(jtfSenha);
        jp3.add(jbLogar);
        jp3.add(jbSair);

        jPanel.add("North",jp1);
        jPanel.add("Center",jp2);
        jPanel.add("South",jp3);

        setTitle("Login");
        getContentPane().add(jPanel);
        pack();
        setVisible(true);
    }

    public static void main (String[] args){
        Login log = new Login();
        tc = new TesteCon();
    }

    public void limpar(){
        jtfCod.setText("");
        jtfSenha.setText("");

    }

    public String getJanStat() {
        return janStat;
    }

    public void setJanStat(String janStat) {
        this.janStat = janStat;
    }   

    public void actionPerformed(ActionEvent evento) {
        if(evento.getSource() == jbLogar){
            String js;
            tc.acesso(jtfCod, jtfSenha);
            js = getJanStat();
            if (js == "fechar"){
                this.dispose();
            }
            limpar(); 

        }

        if(evento.getSource() == jbSair){
            System.exit(0);
        }

    }   
}

This is the connection class code.

package teste;

import java.sql.*;
import javax.swing.*;

public class TesteCon{
   private String driver,url;
   Connection conexao;

   Statement stm;
   ResultSet rs;
   Login log;

   public TesteCon(){
    //driver="sun.jdbc.odbc.JdbcOdbcDriver";
   driver="oracle.jdbc.driver.OracleDriver";
    url="jdbc:oracle:thin:guilherme/1997@//localhost:1521/XE";
    conecta(driver,url);
}
public void conecta(String driver, String url){
    try{
    // carrega o driver da ponte jdbc-odbc
    Class.forName(driver);
    // abre conexao com o banco de dados
    conexao=DriverManager.getConnection(url);
    System.out.println("Conexão executada com sucesso");
    //conexao.close();
    }
    catch(SQLException SqlExc){
        System.out.println("Erro de SQL!");
    }

    catch(ClassNotFoundException exc){
        System.out.println("Classe não encontrada!");
    }
    }   

 public void acesso(JTextField jtfCod, JTextField jtfSenha){

    try{
    ResultSet rs;
    Statement stm = conexao.createStatement();
    conecta(driver, url);
    String s, statusLog="";

    String sql = "select * from usuario";
    rs = stm.executeQuery(sql);
    //rs.next();
    while (rs.next()) {
        if(jtfCod.getText().equals(rs.getString("codigo")) 
                && jtfSenha.getText().equals(rs.getString("senha"))){
            statusLog = "on";
            break;
        }
        else{
            statusLog = "off";
            }
    }
    //nesse if eu mostro a msg de acesso permitido, abro a segunda janela e mudo o valor de janStat para poder fechar a jenela.
    if(statusLog=="on"){
        JOptionPane.showMessageDialog(null,"Acesso permitido");

        janela2 jan = new janela2();
        jan.setNome(rs.getString("nome"));// aqui foi apenas um teste para um Label da segunda janela.
        log.setJanStat("fechar");


        }
    else if(statusLog=="off"){
        JOptionPane.showMessageDialog(null,"Acesso negado");

        }
    //criei esse else apenas para testes.
    else{
        JOptionPane.showMessageDialog(null,"ELSE");

        }


    conexao.close();
    } catch(Exception e){
    }
}


public  static void main(String args[]){
        TesteCon ins=new TesteCon();
    }
}
  • What do you mean "not working?". If it is a Jframe, Dispose would solve the problem. Does the window not close even with Dispose or is closing the entire application? You can post a [mcve] from this login window?

  • I put the complete codes.

  • 1

    Additional reading: http://answall.com/a/2095/132

1 answer

3


There are a lot of problems with your code, you’re mixing the layers of screens(views) with layers of communication with the database(models), you’re delegating things to your connection class that she shouldn’t even know exists. In swing, you must start the application inside the (the reasons you can see in this answer and in this one quoted by @Victorstafusa), so I made this change in the code too.

To solve the problem without having to refactor the entire code, I adapted its method acesso so that it receives only the strings containing the login and password, validate and return if successful through a boolean. So you restrict its use, which is just check if the login is valid.

In your login class, you must receive the return and from there take an action, that is, if the return was true, you open the new window and call the Dispose from the current login window, if it is false you display the invalid login message and clear the fields.

Follows the two amended classes:

Login class as it should be:

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

public class Login extends JFrame implements ActionListener {

    private JPanel jPanel, jp1, jp2, jp3;
    private JLabel lbSenha, lbCod;
    private JTextField jtfSenha, jtfCod;
    private JButton jbLogar, jbSair;
    private TesteCon tc;
    private String janStat;

    Login() {
        jPanel = new JPanel(new BorderLayout());
        jp1 = new JPanel();
        jp2 = new JPanel();
        jp3 = new JPanel();

        lbSenha = new JLabel("Senha:");
        lbCod = new JLabel("Codigo:");

        jtfSenha = new JTextField(10);
        jtfCod = new JTextField(10);

        jbLogar = new JButton("Logar");
        jbLogar.addActionListener(this);
        jbSair = new JButton("Sair");
        jbSair.addActionListener(this);

        jp1.add(lbCod);
        jp1.add(jtfCod);
        jp2.add(lbSenha);
        jp2.add(jtfSenha);
        jp3.add(jbLogar);
        jp3.add(jbSair);

        jPanel.add("North", jp1);
        jPanel.add("Center", jp2);
        jPanel.add("South", jp3);

        setTitle("Login");
        getContentPane().add(jPanel);
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                Login log = new Login();
            }
        });
    }

    public void limpar() {
        jtfCod.setText("");
        jtfSenha.setText("");

    }

    public String getJanStat() {
        return janStat;
    }

    public void setJanStat(String janStat) {
        this.janStat = janStat;
    }

    public void actionPerformed(ActionEvent evento) {
        if (evento.getSource() == jbLogar) {
            String js;
            tc = new TesteCon();
            boolean logado = tc.acesso(jtfCod.getText(), jtfSenha.getText());
            if (logado) {

                //aqui você troca pela chamda da sua outra tela
                SuaNovaJanela novaJan = new SuaNovaJanela();
                novaJan.setVisible(true);

                this.dispose();
            } else {
                JOptionPane.showMessageDialog(null, "Login inválido");
                limpar();
            }
        }

        if (evento.getSource() == jbSair) {
            System.exit(0);
        }

    }
}

Testecon class:

import java.sql.*;

public class TesteCon {

    private String driver, url;
    Connection conexao;

    Statement stm;
    ResultSet rs;
    Login log;

    public TesteCon() {
        //driver="sun.jdbc.odbc.JdbcOdbcDriver";
        driver = "oracle.jdbc.driver.OracleDriver";
        url = "jdbc:oracle:thin:guilherme/1997@//localhost:1521/XE";
        conecta(driver, url);
    }

    public void conecta(String driver, String url) {
        try {
            // carrega o driver da ponte jdbc-odbc
            Class.forName(driver);
            // abre conexao com o banco de dados
            conexao = DriverManager.getConnection(url);
            System.out.println("Conexão executada com sucesso");
            //conexao.close();
        } catch (SQLException SqlExc) {
            System.out.println("Erro de SQL!");
        } catch (ClassNotFoundException exc) {
            System.out.println("Classe não encontrada!");
        }
    }

    public boolean acesso(String jtfCod, String jtfSenha) {
        boolean logou = false;
        try {
            ResultSet rs;
            Statement stm = conexao.createStatement();
            conecta(driver, url);

            String sql = "select * from usuario";
            rs = stm.executeQuery(sql);
            //rs.next();
            while (rs.next()) {
                if (jtfCod.equals(rs.getString("codigo"))
                        && jtfSenha.equals(rs.getString("senha"))) {
                    logou = true;
                    break;
                }
            }

            conexao.close();
        } catch (Exception e) {
        }

        return logou;
    }
}

There are other problems with the two classes, but it is not appropriate to comment here not to extend too much the answer leaving the focus of the question.

  • Now it’s working, thank you very much for your help.

  • @Guilhermesouza good that it worked :D you can mark the answer as accepted by clicking on v the left. Thus, it will serve as a reference for other people.

Browser other questions tagged

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