如何从另一个方法访问变量(按钮)

时间:2016-09-26 16:48:32

标签: java swing

如何访问变量'按钮'来自actionlistner方法?

我正在努力让程序打印出来,点击按钮' (System.out.println(""))只要单击按钮,就会进入控制台。我怎么做?

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)
    {

    }

}
}

1 个答案:

答案 0 :(得分:0)

使button成为一个类变量(所谓的字段),而不是buildframe()方法中的局部变量。

这里有一个小例子:

class MyClass {
    Object myField;

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

    void anotherMethod() {
        myField.aMethod();
    }
}