Issue
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
.
Why is this? What have I done wrong in this code?
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");
}
}
Solution
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/
Answered By - AntoineB
Answer Checked By - Mary Flores (JavaFixing Volunteer)