2016-09-26 176 views
-2

如何從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) 
    { 

    } 

} 
} 
+0

促進'button'到Game'的'場。現在,它的作用域爲'Game#buildFrame'。 – mre

+0

你需要閱讀變量*作用域*,因爲你的問題就是關於這個 - 變量在你的類的方法不可見的範圍內。 –

回答

0

button使類變量(所謂的場),而不是在buildframe()方法的局部變量。

這裏有一個小例子給你:

class MyClass { 
    Object myField; 

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

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

我可以用'JButton'替換'Object'嗎?此外,該方案仍然無法正常工作。我只是希望它能夠在按下按鈕時向控制檯輸出一些信息 – arcturus125

+0

不,你不能簡單地把它換成JButton,這個例子就是關於如何在java中創建一個字段。如果你不知道我的意思,你可能想要搜索一些關於「java變量作用域」的教程。 –

相關問題