将多个jcomponents绘制到框架

问题描述 投票:0回答:1

在我的观众课程中:

JFrame f = new JFrame(); initializeFrame(f); Car x = new Car(100, 100); Car y = new Car(300, 300); f.add(x); f.add(y);

尽管坐标似乎有所不同,但只有最后一辆汽车被绘制。
有任何建议吗?谢谢
    

您想做的是使用
Car
对象的数据结构,然后在

paintComonent

方法中循环循环。像

List<Car> cars = new ArrayList<>(); .... @Override protected void paintComponent(Graphics g) { super.paintComponent(g); for (Car car : cars) { car.drawCar(g); } }
java swing user-interface graphics paintcomponent
1个回答
15
投票
方法将来自您的

drawCar

Car


请参见更多示例

here
hore

hore
here
hore

hore

Here

. update 这里是一个简单的示例,使用一些“法拉利”我也使用了一些动画,但是我上面有相同的基本点。 public class Car { int x, y; public Car(int x, int y) { this.x = x; this.y = y; } public void drawCar(Graphics g) { g.setColor(Color.BLACK); // do everything here as you would in a paintComponent method } }


但看来他们正在互相覆盖。

jframe的默认布局管理器是BorderLayout。因此,默认情况下,您将所有组件添加到BorderLayout的中心。但是,您只能在中心添加一个组件,因此只显示最后一辆汽车。

将布局管理器更改为flowlayout以查看差异。 或者,看来您正在尝试以随机位置绘制汽车,在这种情况下,您应该使用“空”布局。然后,您将负责设置每个汽车组件的大小/位置。

enter image description here我可以将所有编程的代码放在一起?


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.