How to close one screen after opening another?

2

I'm having trouble closing the 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 gained access, and then a second second window should open. So far so good, but I'm having trouble closing the Login window only 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();
    }
}
    
asked by anonymous 17.09.2016 / 01:12

1 answer

3

You have several problems with your code, you are mixing the layers of views with layers of communication with the database, you are delegating things to your connection class that it should not even have an idea of. In swing, you should start the application within the (the reasons you can see in this answer and nest here quoted by @ VictorStafusa ), so I made this change in code as well.

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

In your login class, you should receive the return and from there take an action, that is, if the return was true, you open the new window and call the current login window's dispose, if false displays the invalid login message and clears the fields.

The following two classes are changed:

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);
        }

    }
}

TestCon 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 both classes, but it is not necessary to comment here to not extend the answer too far out of the question.

    
17.09.2016 / 02:29