初学者的问题。无法在主方法之外访问类实例方法?

I'm working through the book "Head first Java" and started chapter 12. When I tried to create the method changeButtonText() I cannot access any of the class methods from button.

为什么是这样?我在这段代码中做错了什么?

import javax.swing.*;

public class Main {

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        JButton button = new JButton("Click Me");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().add(button);

        frame.setSize(300,300);
        frame.setVisible(true);

    }

    public void changeButtonText(){
        button.setText("I've been clicked");
    }
}
评论
  • wfuga
    wfuga 回复

    您的代码有几处错误。让我们从Button开始。

    public void changeButtonText(){
        button.setText("I've been clicked");
    }
    

    First we need to talk about scopes. A scope is what's declared between { /* here */ } i.e. two curly brackets. From within a scope you can access and declare both local and global objects, variables, members etc.

    因此,这是一个使用本地范围的示例:

    public void myFunction(){
        JButton button = new Jbutton();
    }
    

    If I then go ahead and try to access the button outside of the scope, it wont know what button is. Since it's not declared within that local scope.

    public void myFunction(){
        JButton button = new Jbutton();
    }
    button.Text = "hello"; //error
    

    全球范围:

    JButton button = new JButton(); //declaring button in global scope
    public void myFunction(){
        this.button.Text = "hello"; // will access the globally declared variable, object, member called button.
    }
    
  • wsed
    wsed 回复

    The reason you cannot access the variable is because of its scope (tutorial about the scope of variables: https://www.baeldung.com/java-variable-scope).

    You declare the variable JButton button in the main method, therefore it is not accessible anywhere outside of it, even in a method that main calls itself.

    To make changeButtonText aware that the button variable exists, you have to pass it as parameters of this method:

    import javax.swing.*;
    
    public class Main {
    
        public static void main(String[] args) {
            JButton button = new JButton("Click Me");
    
            changeButtonText(button);
        }
    
        public static void changeButtonText(JButton button){
            button.setText("I've been clicked");
        }
    }
    

    I also added the static keyword in front of the changeButtonText method, because main is also a static method. Check this link for example to have more details about the difference: https://www.geeksforgeeks.org/static-methods-vs-instance-methods-java/