Java only allowing global variables to be static?

后端 未结 5 569
难免孤独
难免孤独 2021-01-19 01:40

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

5条回答
  •  忘掉有多难
    2021-01-19 02:33

    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.

提交回复
热议问题