仅一个对象将渲染到屏幕 [英] Only one object will Render to Screen

查看:79
本文介绍了仅一个对象将渲染到屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使两个正方形都出现在JFrame上,但是只有我在主方法apperas中最后一个出现的正方形,而另一个没有.大约3个小时以来,我们一直在努力解决这个问题,并且想要粉碎我的计算机屏幕.任何帮助都是极好的.谢谢.

I'm trying to make it so that both squares appear on the JFrame but only the one that I make last in the main method apperas and the other one does not. Have been trying to figure this out for about 3 hours now and wanna smash my computer screen. Any help would be AWESOME. Thank you.

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

}
}

推荐答案

静态变量属于类而不是对象. 对Enemy头寸使用静态变量意味着,如果您创建Enemy类的任何实例,它们将共享相同的静态x,y.您有2个正方形,但它们总是彼此重叠.

Static variables belongs to classes not objects. Using static variables for Enemy positions means that if you create any instances of Enemy class they will share the same static x, y. You have 2 squares but they are always on top of each other.

public static int x, y;更改为public int x, y;应该可以解决您的问题.

Changing public static int x, y; to public int x, y; should solve your problem.

这篇关于仅一个对象将渲染到屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆