gpt4 book ai didi

java - 单击Java时绘制多辆车

转载 作者:行者123 更新时间:2023-12-01 10:49:01 24 4
gpt4 key购买 nike

我已经编写了一个程序,当我单击鼠标按钮时绘制 1 辆汽车,现在我想在第二次单击鼠标按钮时再绘制 1 辆汽车。

@SuppressWarnings("serial")

公共(public)类 CarMove 扩展 JComponent

{

private volatile boolean drawCar = false;
private volatile boolean drawCar1 = false;

private int lastX = 0;
private int clickCount = 0;

{
FrameMouseListener listener = new FrameMouseListener();
super.addMouseListener(listener);
}

public CarMove()
{
Thread animationThread = new Thread(new Runnable()
{
public void run()
{
while (true)
{
repaint();
try
{
Thread.sleep(10);

} catch (Exception ex) {}
}
}
});

animationThread.start();
}
public void paintComponent(Graphics g)
{

Graphics2D g2 = (Graphics2D) g;

if (drawCar)
{
int x = 1;
int carSpeed = 1;
int w = getWidth();
x = lastX + carSpeed;
//create the car from draw class
Car car1 = new Car(x,320);
car1.draw(g2);
lastX = x;
}
if (drawCar1)
{
int x = 1;
int carSpeed = 1;
int w = getWidth();
x = lastX + carSpeed;
//create the car from draw class
Car car2 = new Car(x,320);
car2.draw(g2);
lastX = x;
}
}
public class FrameMouseListener implements MouseListener
{

@Override
public void mouseClicked(MouseEvent ev)
{
if (clickCount == 1)
{
drawCar = true;
repaint();
}
if (clickCount == 2)
{
drawCar1 = true;
repaint();
}

}

我尝试创建 boolean 绘图两次,但没有成功,请帮助我。

最佳答案

如果您需要知道用户单击鼠标按钮的次数。

@Override
public void mouseReleased(MouseEvent m) {
int clickCount = m.getClickCount();

//change your code to do draw the cars based on clicks
}

编辑:

当你调用重绘方法时,第一行必须是:

super.repaint();

要绘制多辆汽车,您必须在调用 paint(Graphics g) 时使用循环,如下所示:

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

Graphics2D g2 = (Graphics2D) g;

for(int car=0; car<totalClicks; car++){

//Here add your code to draw the cars
if(car==1){
//do this
}else if(car==2){
//do that
}else if(car== 3){
//do more
}else if(car==4){
//hard job
}//etc

}

关于java - 单击Java时绘制多辆车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34029078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com