2016-09-26 10 views
-2

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

    } 

} 
} 
+0

'' Game'のフィールドにbutton'を推進しています。今、 'Game#buildFrame'にスコープされています。 – mre

+0

変数はスコープ内にあり、クラスのメソッドでは見えないボタン変数が問題であるため、変数* scope *を読み上げたいと思うでしょう。 –

答えて

0

代わりbuildframe()方法でローカル変数のbutton(そのフィールドと呼ばれる)クラス変数を作成します。

ここではあなたのために少し例を示します

class MyClass { 
    Object myField; 

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

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

私は 'JButton'のための 'オブジェクト'を交換することができますか?また、プログラムはまだ動作しません。ボタンを押したときにコンソールに何かを印刷したいだけです。 – arcturus125

+0

いいえ、単にJButton用にスワップすることはできません。例はJavaでフィールドを作成する方法です。私がこれで何を意味するのかわからない場合は、 "java variable scope"に関するチュートリアルを検索したいかもしれません。 –

関連する問題