23k
23k

Reputation: 1399

Changing a JButton on click event

I'm trying to do something very simple, change the text in a button when it has been clicked.

I can't seem to get it to work, can someone show me the correct place to add an ActionListener?

Main Class

public class ATM implements ActionListener{

  public static void main(String[] args) {
      atmGUI gui = new atmGUI();        
      gui.login();      
  }
}

atmGUI Class

public class atmGUI implements ActionListener {

public JTextField usernameField;
public JTextField pinField;
public String userName;
public int pin;

/**
 * @wbp.parser.entryPoint
 */

public void login() {

    JFrame frame = new JFrame();
    frame.getContentPane().setLayout(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 300);
    frame.setTitle("Virtual Bank Account");

    JLabel lblUsername = new JLabel("Username");
    lblUsername.setBounds(16, 88, 82, 16);
    frame.getContentPane().add(lblUsername);

    usernameField = new JTextField();
    usernameField.setBounds(13, 107, 124, 28);
    frame.getContentPane().add(usernameField);
    usernameField.setColumns(10);

    JLabel lblPin = new JLabel("PIN");
    lblPin.setBounds(16, 140, 61, 16);
    frame.getContentPane().add(lblPin);

    pinField = new JTextField();
    pinField.setBounds(13, 157, 124, 28);
    frame.getContentPane().add(pinField);
    pinField.setColumns(10);

    JButton btnLogin = new JButton("Login");
    btnLogin.setBounds(355, 232, 117, 29);
    btnLogin.addActionListener(new ActionListener(){
        btnLogin.setText("Clicked");
    });
    frame.getContentPane().add(btnLogin);


    frame.setResizable(false);
    frame.setAlwaysOnTop(true);
    frame.setVisible(true);

}

}

EDIT :

Here is the error that is produced

The type new ActionListener(){} must implement the inherited abstract method ActionListener.actionPerformed(ActionEvent)

Upvotes: 0

Views: 2787

Answers (3)

Thanh Le
Thanh Le

Reputation: 773

add function anonymous

btnLogin.addActionListener(new ActionListener(){

       //do something
       //lblUsername.setText("blah blah");
    });

Detail:

btnLogin.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                //do something
                //lblUsername.setText("blah blah");
            }
        });

Upvotes: 2

Ved
Ved

Reputation: 369

You will need to add the onActionPerformed(ActionEvent) method to your atmgui class, do it like:

public void onActionPerformed(ActionEvent avt)
{
    //code to handle the button click
}

OR You can also use it while initializing the JButton:

JButton b=new JButton("Click Me!" );
b.addActionListener(new ActionListener() {
    //handle the button click here
}

Upvotes: 1

Mahmoud Hanafy
Mahmoud Hanafy

Reputation: 8228

You should implement the actionperformed() method inside your atmGUI class to handle the clicked action.

Upvotes: 1

Related Questions