Java:无法从同一个包中的其他类访问静态变量

时间:2011-10-16 11:19:40

标签: java eclipse static

这很奇怪,因为我有一个可以访问Frame.dimension.getWidth()的Character类;和它的伙伴getHeight(),但是当我想在Map类中使用它时eclipse强调它并且不能给我反馈。无论如何运行程序最终会导致java错误,说明他们无法找到Map对象的X值。

这是Frame类:

package Core;

import java.awt.Dimension;
import java.awt.Rectangle;
import javax.swing.JFrame;


public class Frame
{
static int width = 800, height = 600;
static Dimension dimension;

public static void main(String[]args){
    JFrame frame= new JFrame("RETRO");
    frame.add(new Screen());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(width,height);
    frame.setVisible(true);
    frame.setResizable(false);
    dimension = frame.getContentPane().getSize();
}
}

Map类:

package Core;

import java.awt.Frame;
import java.awt.Image;
import java.awt.Rectangle;
import javax.swing.ImageIcon;
import java.awt.Dimension;

public class Map
{
    double x, y;

Image map;
ImageIcon background = new ImageIcon("images/Maps/maze.jpg");

public Map(){
    map = background.getImage();
}

public void move(double moveX, double moveY){
        x += moveX;
        y += moveY;
}

//////////Gets
public Image getMap(){
    return map;
}
public double getX(){
    if(x<0)
        x=0;
    else if(x>Frame.dimension.getWidth())
        x=Frame.dimension.getWidth();

    return x;
}

public double getY(){
    if(y<0)
        y=0;
    else if(y>Frame.dimension.getHeight())
        y=Frame.dimension.getHeight();

    return y;
}

public int getHeight(){
    return map.getHeight(null);
}

public int getWidth(){
    return map.getWidth(null);
}
}

我可以提供Character类,但它现在非常漫长而且很混乱..但是Frame这个词只用于调用Frame.dimension.getWidth()/ getHeight();

4 个答案:

答案 0 :(得分:1)

您在x=Frame.dimension.getWidth();中引用的Frame类是java.awt.Frame。请注意您导入了此类。如果您不使用此类,请尝试明确提及:Core.Frame或删除行import java.awt.Frame;

答案 1 :(得分:1)

您可能与自己的Core.Frame和Java自己的java.awt.Frame有名称冲突。

我会将您的Frame类重命名为与核心Java名称不同的东西,并且我也避免使用静态变量。

答案 2 :(得分:1)

您的Map课程指的是java.awt.Frame(您导入的),而不是Core.Frame

如果你真的需要保留import java.awt.Frame,只需在引用它时使用框架类的完全限定名称(Core.Frame)以避免碰撞,例如在getX方法中:

public double getX(){
    if(x<0)
        x=0;
    else if(x>Core.Frame.dimension.getWidth())
        x=Core.Frame.dimension.getWidth();

    return x; 
}

或者,如果您根本不需要使用java.awt.Frame,只需删除该import行。

答案 3 :(得分:0)

似乎java.awt.Frame和Core.Frame之间的导入存在冲突

您应该在导入中添加“import static Core.Frame.dimension”,然后使用“dimension”而不是“Frame.dimension”

相关问题