Java Swing GUI Login Action listener Error

Franc :

Hi I'm trying to create a Java GUI Login using raw coding however I've encountered one error during the Java Action Listener which doesn't check whether the login system does have the the requirement and send the text.

This is how it should run:

add username label and text 
add password label and text
add success label and text
checks username text input *
checks password text and input *
send success label to the JLabel *

*this markings are the three checking that isn't working at all. the first 3 does appear but the last 3 doesn't appear at all.

this is the code that i have tried to run

button.addActionListener(this);
button.addActionListener(new Login());

I've tried using this two method and it doesn't seems to work.

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

public class Login implements ActionListener {

    private JFrame frame;
    private JPanel panel;
    private JLabel username;
    private JTextField user;
    private JLabel password;
    private JPasswordField pass;
    private JButton button;
    private JLabel success;

    public Login(){
        frame = new JFrame();
        panel = new JPanel();

        frame.setSize(350,200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        panel.setLayout(null);

        username = new JLabel("User");
        username.setBounds(10,20,200,25);
        panel.add(username);

        user =  new JTextField(20);
        user.setBounds(100,20,200,25);
        panel.add(user);

        password = new JLabel("Password");
        password.setBounds(10,50,80,25);
        panel.add(password);

        pass = new JPasswordField(20);
        pass.setBounds(100,50, 200 ,25);
        panel.add(pass);

        button = new JButton ("Login");
        button.setBounds(10,80,80,25);
        button.addActionListener(this);
        panel.add(button);

        success = new JLabel(""); 
        success.setBounds(10, 110, 300, 25);
        panel.add(success);


        frame.setVisible(true);
    }
    public static void main (String[] args ){
        new Login();
    }
    @Override
    public void actionPerformed(ActionEvent e){
        String user = username.getText();
        String password = pass.getText();

       if (user.equals("Someone") && password.equals("Someone")){
            success.setText("Success");
        }
    }
}

is there any way to resolve it

Andrew Thompson :

A little debugging would have shown that the code in the actionPerformed(..) method was getting the text of the user label rather than the text field.

Change:

//String user = username.getText();
String userString = user.getText();

And:

//if (user.equals("Someone") && password.equals("Someone")) {
if (userString.equals("Someone") && password.equals("Someone")) {

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=417092&siteId=1