如何從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)
{
}
}
}
促進'button'到Game'的'場。現在,它的作用域爲'Game#buildFrame'。 – mre
你需要閱讀變量*作用域*,因爲你的問題就是關於這個 - 變量在你的類的方法不可見的範圍內。 –