2016-10-04 57 views
1

我试图让这两个方块出现在JFrame上,但只有我在主要方法的最后一个出现而另一个没有出现。一直试图找出现在约3小时,并想粉碎我的电脑屏幕。任何帮助都是极好的。谢谢。只有一个对象会渲染到屏幕

public class Main extends JFrame{ 

static Main main; 
static Enemy square, square2; 
Render render; 

Main(){ 

    render = new Render(); 

    setVisible(true); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setSize(500,500); 
    setResizable(false); 
    add(render); 
} 

public void render(Graphics2D g){ 

    square.render(g); 
    square2.render(g); 
} 

public static void main(String [] args){ 

    main = new Main(); 

    square2 = new Square(300,50); 
    square = new Square(50,50); 
} 


} 

.....

public class Render extends JPanel { 

public void paintComponent(Graphics g){ 
    super.paintComponent(g); 

    Main.main.render((Graphics2D)g); 

} 
} 

......

public class Enemy { 

public static int x,y; 

Enemy(int x, int y){ 
    this.x = x; 
    this.y = y; 

} 

public void render(Graphics2D g){ 

} 
} 

.......

public class Square extends Enemy { 

Square(int x, int y){ 
    super(x,y); 
} 

public void render(Graphics2D g){ 

    g.setColor(Color.red); 
    g.fillRect(x, y, 50, 50); 

} 
} 

回答

2

静态变量属于类不是对象。 为敌人位置使用静态变量意味着如果您创建Enemy类的任何实例,它们将共享相同的静态x,y。你有2个方格,但它们总是彼此重叠。

public static int x, y;更改为public int x, y;应解决您的问题。

+0

非常感谢你! –