java全局变量 静态变量,Java只允许全局变量是静态的?

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) {

}

}

}

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值