Java只允许全局变量是静态的? [英] Java only allowing global variables to be static?
问题描述
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);
}
类makeMapListener实现ActionListener {
public void actionPerformed(ActionEvent e){
$ b}
}
$ b $ <$ code>
$ c> main 方法是 static
,所以它只能访问 static
字段该班直接。否则,您需要首先创建 PlannerMain
的实例,然后才能访问其字段。 I.e。
public static void main(String [] args){
PlannerMain planner = new PlannerMain();
planner.frame =新的JFrame(Land Planner);
planner.makeMap = new JButton(Make Map);
planner.makeMap.addActionListener(new makeMapListener());
...
}
请注意,这样的初始化代码最好放在一个构造函数方法。
你引用的变量不是全局变量。现在你有许多独立的
frame 和 makeMap
多少个 PlannerMain
您创建。如果你声明它们是 public static
- 在这种情况下,所有的 PlannerMain $ c,它们只会是全局的 $ c>实例将共享相同的框架
和 makeMap
,外部世界也会看到它们。
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.
这篇关于Java只允许全局变量是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!