Java only allowing global variables to be static?

后端 未结 5 550
难免孤独
难免孤独 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条回答
  •  萌比男神i
    2021-01-19 02:16

    In java the entry point - the main method must be static, therefore any class variables it accesses must also be static.

    To avoid having static member variables spawn out all over the code (which is bad) from this do the following:

    public class PlannerMain {
    
     JFrame frame;
    
     JButton makeMap;
    
     public static void main(String[] args){
         PlannerMain theApp = new PlannerMain();
         theApp.init();
     }
    
     private void init() {
         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) {
    
    
    
            }
    
        }
    }
    

    Now your static main method creates a concrete (non-static) instance of your PlannerMain class so it can use the member variables.

提交回复
热议问题