-1

how do i access the variable 'button' from the actionlistner method?

i am trying to get the program to print 'button clicked' (System.out.println("")) to the console whenever the button is clicked. how do i do that?

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

import javax.swing.*;

public class Game implements ActionListener
{

public static void main(String[] args) 
{
    new Game().buildframe();
}

public void buildframe()
{

    //making the frame
    JFrame frame = new JFrame("Game");
    GridLayout table = new GridLayout(5,1);
    frame.setLayout(table);

    //creating the labels and textfields
    JLabel usernameLabel = new JLabel("Username;");
    JTextField username = new JTextField("");
    JLabel passwordLabel = new JLabel("Password:");
    JTextField password = new JTextField("");

    //create the button and action listener
    JButton button = new JButton();
    button.setText("Login");
    button.addActionListener(this);

    //adding the components
    frame.add(usernameLabel);
    frame.add(username);
    frame.add(passwordLabel);
    frame.add(password);
    frame.add(button);

    //sdets the size of the Jframe
    frame.setSize(300, 150);
    //puts the JFrame in the midle of the screen
    frame.setLocationRelativeTo(null);
    //setws the default operation when the user tries to close the jframe
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

}
public void actionPerformed(ActionEvent evt) 
{
    if(evt.getSource() == button)
    {

    }

}
}
mre
  • 43,520
  • 33
  • 120
  • 170
arcturus125
  • 11
  • 1
  • 2

1 Answers1

1

Make button a class variable (so called field) instead of a local variable in the buildframe() method.

Here's a little example for you:

class MyClass {
    Object myField;

    void aMethod() {
        myField = new Object();
    }

    void anotherMethod() {
        myField.aMethod();
    }
}
Alvin L-B
  • 488
  • 2
  • 8
  • can i swap 'Object' out for 'JButton'? also, the program still doesn't work. i just want it to print something out to the console when the button is pressed – arcturus125 Sep 26 '16 at 17:35
  • No, you can't simply swap it out for JButton, the example was just on how to create a Field in java. If you do not know what I mean by this, you might want to search for some tutorials about "java variable scope". – Alvin L-B Sep 26 '16 at 18:59