2016-10-13 55 views
0

如何才能識別button 2do_something函數?點擊後我想更改button2文字,但我收到一個錯誤:button2 cannot be resolved通過函數Java Swing對象識別

class myClass { 
    public static int counter = 0; 
    public static void do_something() { 
    button2.setText(Integer.toString(counter)); 
    } 

public static void main(String[] args) { 
    JFrame frame = new JFrame(); 
    frame.setLayout(new GridLayout(3, 2)); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    JButton button = new JButton("button 1"); 
    frame.add(button); 
    JButton button2 = new JButton("button 2"); 
    button2.addActionListener(e -> do_something()); 
    frame.add(button2); 
    frame.pack(); 
    frame.setVisible(true);  
    } 
} 
+1

這是一個範圍的問題。請看看這個問題,讓我們知道它是否解決您的問題:http://stackoverflow.com/questions/4560850/java-variable-scope – ControlAltDel

回答

0

需要聲明buttonbutton2外部類(一些如何在全球範圍並增加counter varaiable每當按button2):

package javaapplication1; 

import java.awt.GridLayout; 
import javax.swing.JButton; 
import javax.swing.JFrame; 

class myClass extends JFrame{ 

    static JButton button = new JButton("button 1"); 
    static JButton button2 = new JButton("button 2"); 
    public static int counter = 0; 

    public static void do_something() { 
     counter++; 
     button2.setText(Integer.toString(counter)); 
    } 

    public static void main(String[] args) { 
     JFrame frame = new JFrame(); 
     frame.setLayout(new GridLayout(3, 2)); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     frame.add(button); 

     button2.addActionListener(e -> do_something()); 
     frame.add(button2); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
}