我的目标是创造一个随机的汽车或卡车十次,应该有一个随机的位置。当我尝试向我的JFrame添加大量JPanel时,只会出现一个JPanel。如何调用方法randomVehicle()一次绘制多个Vehicle,我尝试添加print语句并检查逻辑,但我不知所措。
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class GraphicsTester {
public static void main(String[] args) {
//1. Create the frame.
JFrame frame = new JFrame();
//2. Optional: What happens when the frame closes?
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//4. Size the frame.
frame.setSize(2000, 2000);
//5. Show it.
Vehicle frame1 = new Vehicle();
frame.add(frame1.randomVehicle());
frame.add(frame1.randomVehicle());
frame.setVisible(true);
}
}
车辆类
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
public class Vehicle extends JPanel {
public Vehicle() {
xPos = (int) (Math.random() * 500) + 1;
yPos = (int) (Math.random() * 500) + 1;
}
public Vehicle randomVehicle() {
int vehicleRandom = (int) (Math.random() * 2) + 1;
System.out.println(vehicleRandom);
if (vehicleRandom==1) {
return new Car();
}
if (vehicleRandom==2) {
return new Truck();
}
return null;
}
protected int xPos;
protected int yPos;
}
汽车
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
public class Car extends Vehicle {
public Car() {
super();
System.out.println(xPos);
System.out.println(yPos);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.draw(new Rectangle(xPos + 100, yPos + 100, 200, 50));
g2d.draw(new Rectangle(xPos + 150, yPos + 85, 100, 15));
g2d.draw(new Ellipse2D.Double(xPos + 120, yPos + 150, 50, 35));
g2d.draw(new Ellipse2D.Double(xPos + 220, yPos + 150, 50, 35));
}
}
卡车
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
public class Truck extends Vehicle {
public Truck() {
super();
System.out.println(xPos);
System.out.println(yPos);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.draw(new Rectangle(xPos + 100, yPos + 100, 50, 75));
g2d.draw(new Ellipse2D.Double(xPos + 110, yPos + 175, 35, 35));
g2d.draw(new Rectangle(xPos + 180, yPos + 70, 350, 106));
g2d.draw(new Ellipse2D.Double(xPos + 190, yPos + 175, 35, 35));
g2d.draw(new Ellipse2D.Double(xPos + 225, yPos + 175, 35, 35));
g2d.draw(new Ellipse2D.Double(xPos + 475, yPos + 175, 35, 35));
g2d.draw(new Ellipse2D.Double(xPos + 440, yPos + 175, 35, 35));
}
}
答案 0 :(得分:0)
使用for循环..如下所示..
Vehicle frame1 = new Vehicle();
for(int i=0;i<10;i++) {
frame.add(frame1.randomVehicle());
}
frame.setVisible(true);