Search code examples
javaglobal-variables

Java only allowing global variables to be static?


So I just started coding a Java program I'm writing and it's telling me that my global variables need to be static. I don't understand why it's telling me this because I've developed Java programs before without having to make my global variables static. Could someone please help?

 import java.awt.event.*;
 import javax.swing.*;

 public class PlannerMain {
      JFrame frame;
      JButton makeMap;

      public static void main(String[] args){
           frame = new JFrame("Land Planner");
           makeMap = new JButton("Make Map");
           makeMap.addActionListener(new makeMapListener());
           frame.setSize(580,550);
           frame.setVisible(true);
      }

      class makeMapListener implements ActionListener{

              public void actionPerformed(ActionEvent e) {

              }
      }

}

Solution

  • Your main method is static, so it can access only the static fields of the class directly. Otherwise, you need to create an instance of PlannerMain first, then you can access its fields. I.e.

    public static void main(String[] args){
      PlannerMain planner = new PlannerMain();
      planner.frame = new JFrame("Land Planner");
      planner.makeMap = new JButton("Make Map");
      planner.makeMap.addActionListener(new makeMapListener());
      ...
    }
    

    Note that such initialization code is better put in a constructor method.

    Btw the variables you refer to are not global. Right now you have as many distinct frame and makeMap as many instances of PlannerMain you create. They would only be "global" (or its closest equivalent in Java) if you declared them public static - in this case all PlannerMain instances would share the same frame and makeMap, and the external world would see them as well.