actionlistnerメソッドから変数 'button'にアクセスするにはどうすればよいですか?別のメソッドから変数(ボタン)にアクセスする方法
ボタンをクリックするたびに、ボタンクリック(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)
{
}
}
}
'' Game'のフィールドにbutton'を推進しています。今、 'Game#buildFrame'にスコープされています。 – mre
変数はスコープ内にあり、クラスのメソッドでは見えないボタン変数が問題であるため、変数* scope *を読み上げたいと思うでしょう。 –