现在,我有一个Brick.java,其中包含我想在BreakoutCourt.java中使用的Levels枚举,它包含在同一个包中,即(默认包)。
当我写入导入Brick.level时;在BreakoutCourt中,我收到一条消息,指出导入块无法解析。即使我写了import static Brick.Level,我也会得到那条消息。
Brick.java中包含的级别枚举如下所示:
public class Brick {
public static final int BWIDTH = 60;
public static final int BHEIGHT = 20;
private int xPos, yPos;
private Level brickLevel;
//This sets up the different levels of bricks.
enum Level{
LUNATIC (4, 40, Color.MAGENTA),
HARD (3, 30, Color.PINK),
MEDIUM (2, 20, Color.BLUE),
EASY (1, 10, Color.CYAN),
DEAD (0, 0, Color.WHITE);
private int hitpoints;
private int points;
private Color color;
Level(int hitpoints, int points, Color color){
this.hitpoints = hitpoints;
this.points = points;
this.color=color;
}
public int getPoints(){
return points;
}
public Color getColor(){
return color;
}
}
//rest of brick class goes under the enum
我在BreakoutCourt中使用它:
//Generates the bricks.
for(int i = 0; i < 8; ++i){
ArrayList<Brick> temp = new ArrayList<Brick>();
Level rowColor = null;
switch(i){
//There are two rows per type of brick.
case 0:
case 1:
rowColor = Level.EASY;
break;
case 2:
case 3:
rowColor = Level.HARD;
break;
case 4:
case 5:
rowColor = Level.LUNATIC;
break;
case 6:
case 7:
default:
rowColor = Level.MEDIUM;
break;
}
for(int j = 0; j < numBrick; j++){
Brick tempBrick = new Brick((j * Brick.BWIDTH), ((i+2) * Brick.BHEIGHT), rowColor);
temp.add(tempBrick);
}
我做错了什么?谢谢你的帮助!
答案 0 :(得分:4)
如果要导入班级成员,则需要使用static import。所以你可以这样做:
import static Brick.Level;
但要小心。应该谨慎使用静态导入,如链接页面所述。在没有静态导入的情况下执行此操作的另一种方法是使用外部类名。例如:Brick.Level.LUNATIC
原因是在一个较大的项目中,您可能有多个具有Level枚举的类,您必须查看导入以查看正在使用哪个类。
答案 1 :(得分:0)