Fechar a Tela de Login

6 respostas
cavalcant

OLHA SÓ, EU ESTOU USANDO UM jPANEL PARA CRIAR A TELA DE LOGIN E UMA SENHA FIXA, POREM QUANTO EU EXECUTO, ABRIR MAIS NÃO FECHA O LOGIN.

ALGUEM SABE COMO RESOLVER ISSO?

O CODIGO É ESSE:
package PagInicio;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/**String Login = tfLogin.getText();  
String Senha = new String(tfSenha.getPassword());  
UsuarioControl uc = new UsuarioControl();  
UsuarioBean usuario = new UsuarioBean();  
usuario.setLogin("");  
usuario.setSenha("");  
JOptionPane.showMessageDialog(null,"LOGIN OU SENHA INCORRETOS!","ERRO", JOptionPane.WARNING_MESSAGE);
 */
public class Login extends JPanel
        implements ActionListener {

    private static String OK = "ok";
    private static String HELP = "help";
    private static String SAIR = "sair";
    private JFrame controllingFrame; //needed for dialogs
    private JPasswordField passwordField;

    public Login(JFrame f) {

        
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex);
        }
        controllingFrame = f;

        passwordField = new JPasswordField(10);
        passwordField.setActionCommand(OK);
        passwordField.addActionListener(this);

        JLabel label = new JLabel("Enter the password: ");
        label.setLabelFor(passwordField);

        JComponent buttonPane = createButtonPanel();


        JPanel textPane = new JPanel(new FlowLayout(FlowLayout.TRAILING));
        textPane.add(label);
        textPane.add(passwordField);

        add(textPane);
        add(buttonPane);
    }

    protected JComponent createButtonPanel() {
        JPanel p = new JPanel(new GridLayout(0, 1));
        JButton okButton = new JButton("Acessar");
        JButton helpButton = new JButton("Ajuda");
        JButton sairButton = new JButton("Sair");

        okButton.setActionCommand(OK);
        helpButton.setActionCommand(HELP);
        sairButton.setActionCommand(SAIR);
        okButton.addActionListener(this);
        helpButton.addActionListener(this);
        sairButton.addActionListener(this);

        p.add(okButton);
        p.add(helpButton);
        p.add(sairButton);

        return p;
    }

    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();

        if (OK.equals(cmd)) { //Process the password.
            char[] input = passwordField.getPassword();
            if (isPasswordCorrect(input)) {
                new PagPrincipal().setVisible(true);
                this.disable();
                
               
            } else {
                JOptionPane.showMessageDialog(controllingFrame,
                        "Senha Inválida. Tente Novamente.",
                        "Erro",
                        JOptionPane.ERROR_MESSAGE);
            }
            
            Arrays.fill(input, '0');

            passwordField.selectAll();
            resetFocus();
        } else { //The user has asked for help.

            // System.exit(0);

            JOptionPane.showMessageDialog(controllingFrame,
                    "Caso você não tenha senha.\n"
                    + "Entre em Contato com o Administrador\n"
                    + ""
                    + "    Sistema Desenvolvido por Bruno Cavalcante.");

        }
        
        
        
    }


    private static boolean isPasswordCorrect(char[] input) {
        boolean isCorrect = true;
        char[] correctPassword = {'1', '2', '3', '4', '5', '6'};
        

        if (input.length != correctPassword.length) {
            isCorrect = false;
        } else {
            isCorrect = Arrays.equals(input, correctPassword);
        }

        //Zero out the password.
        Arrays.fill(correctPassword, '0');

        return isCorrect;
    }


    protected void resetFocus() {
        passwordField.requestFocusInWindow();
    }

    
    private static void createAndShowGUI() {
       
        JFrame frame = new JFrame("Login");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        
        final Login newContentPane = new Login(frame);
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

       
        frame.addWindowListener(new WindowAdapter() {

            public void windowActivated(WindowEvent e) {
                newContentPane.resetFocus();
            }
        });

        //Display the window.
        frame.pack();
        frame.setVisible(true);
        
        
        
        
        
        // setclosable(false);
        //setResizable(false);
        //Login.setExtendedState(Frame.MAXIMIZED_BOTH);
    }

    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                //Turn off metal's use of bold fonts
                //UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
                UIManager.put("nimbusBase", new Color(152, 135, 105));
                UIManager.put("nimbusBlueGrey", new Color(80, 80, 100));
                UIManager.put("control", new Color(200, 200, 200));
          
                        // setclosable(false);

                
                
            }
        });
    }
    
    

}

6 Respostas

Anime

Oi,

Você é novo no GUJ? Vai criar um tópico e colar seu código-fonte? Leia aqui antes, por favor!
http://www.guj.com.br/posts/list/50115.java

dispose();// fecha o atual
cavalcant

Dispose não funciona!

já tentei setvisible(false); mais não funcionou!

Anime
cavalcant:
Dispose não funciona!

já tentei setvisible(false); mais não funcionou!

Está usando IDE?

Quando for postar código, coloque entre as tags CODE, da uma olhadinha no link que indiquei...

package PagInicio;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Arrays;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/**String Login = tfLogin.getText();
String Senha = new String(tfSenha.getPassword());
UsuarioControl uc = new UsuarioControl();
UsuarioBean usuario = new UsuarioBean();
usuario.setLogin("");
usuario.setSenha("");
JOptionPane.showMessageDialog(null,"LOGIN OU SENHA INCORRETOS!","ERRO", JOptionPane.WARNING_MESSAGE);
*/
public class Login extends JPanel
implements ActionListener {

private static String OK = "ok";
private static String HELP = "help";
private static String SAIR = "sair";
private JFrame controllingFrame; //needed for dialogs
private JPasswordField passwordField;

public Login(JFrame f) {


try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
controllingFrame = f;

passwordField = new JPasswordField(10);
passwordField.setActionCommand(OK);
passwordField.addActionListener(this);

JLabel label = new JLabel("Enter the password: ");
label.setLabelFor(passwordField);

JComponent buttonPane = createButtonPanel();


JPanel textPane = new JPanel(new FlowLayout(FlowLayout.TRAILING));
textPane.add(label);
textPane.add(passwordField);

add(textPane);
add(buttonPane);
}

protected JComponent createButtonPanel() {
JPanel p = new JPanel(new GridLayout(0, 1));
JButton okButton = new JButton("Acessar");
JButton helpButton = new JButton("Ajuda");
JButton sairButton = new JButton("Sair");

okButton.setActionCommand(OK);
helpButton.setActionCommand(HELP);
sairButton.setActionCommand(SAIR);
okButton.addActionListener(this);
helpButton.addActionListener(this);
sairButton.addActionListener(this);

p.add(okButton);
p.add(helpButton);
p.add(sairButton);

return p;
}

public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();

if (OK.equals(cmd)) { //Process the password.
char[] input = passwordField.getPassword();
if (isPasswordCorrect(input)) {
new PagPrincipal().setVisible(true);
this.disable();


} else {
JOptionPane.showMessageDialog(controllingFrame,
"Senha Inválida. Tente Novamente.",
"Erro",
JOptionPane.ERROR_MESSAGE);
}

Arrays.fill(input, '0');

passwordField.selectAll();
resetFocus();
} else { //The user has asked for help.

// System.exit(0);

JOptionPane.showMessageDialog(controllingFrame,
"Caso você não tenha senha.\n"
+ "Entre em Contato com o Administrador\n"
+ ""
+ " Sistema Desenvolvido por Bruno Cavalcante.");

}



}


private static boolean isPasswordCorrect(char[] input) {
boolean isCorrect = true;
char[] correctPassword = {'1', '2', '3', '4', '5', '6'};


if (input.length != correctPassword.length) {
isCorrect = false;
} else {
isCorrect = Arrays.equals(input, correctPassword);
}

//Zero out the password.
Arrays.fill(correctPassword, '0');

return isCorrect;
}


protected void resetFocus() {
passwordField.requestFocusInWindow();
}


private static void createAndShowGUI() {

JFrame frame = new JFrame("Login");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


final Login newContentPane = new Login(frame);
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);


frame.addWindowListener(new WindowAdapter() {

public void windowActivated(WindowEvent e) {
newContentPane.resetFocus();
}
});

//Display the window.
frame.pack();
frame.setVisible(true);





// setclosable(false);
//setResizable(false);
//Login.setExtendedState(Frame.MAXIMIZED_BOTH);
}

public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {

public void run() {
//Turn off metal's use of bold fonts
//UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
UIManager.put("nimbusBase", new Color(152, 135, 105));
UIManager.put("nimbusBlueGrey", new Color(80, 80, 100));
UIManager.put("control", new Color(200, 200, 200));

// setclosable(false);



}
});
}



}

Faz assim e use o dispose depois...

JFrame frame = new JFrame("Login");  
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
lina

Oi,

O dispose() irá funcionar se voce setar no seu construtor a propriedade setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

Tchauzin!

cavalcant

valeu, ta quase funcionando!

O problema é que eu preciso que esse Jpanel feche sozinho quanto colocar a senha e acessar a Tela Principal.

E eu não sei o codigo necessário nem em que linha colocar! alguem sabe isso, por favor!?

R

vc tem 2 soluções:

colocar sua página principal como default, abrindo ela em primeiro com visible(false) e dela chamando a tela de login… dae se o login tiver correto, fazendo dispose da tela de login e dando visible(true) pra tela principal

ou se quiser fazer do modo q está fazendo, vc tem q aprender que criar a telaPrincipal não significa deixar ela aparecendo…

vc faz

new PagPrincipal().setVisible(true);

cria e ja deixa visivel… desse modo o foco sai do formulario de login e senha e vc não consegue dar dispose ou visible nele…

vc poderia criar a tela principal passando o login e senha e na tela principal verificar se está OK… se estiver dae da dispose o login e um visible true na principal, senão NÃO SETA O VISIBLE TRUE e da uma mensagem de erro na tela de login… se vc setar o visible true vc perde o controle da tela de login

Criado 1 de julho de 2011
Ultima resposta 2 de jul. de 2011
Respostas 6
Participantes 4