按下按钮后如何重新制作?当我启动小程序时,它在随机位置随机宽度和高度绘制2个rects,我怎样才能让它们重新生成" respawn"按下按钮后在不同的位置?
package test;
import java.applet.Applet;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class Main extends Applet implements ActionListener{
private static final long serialVersionUID = 1L;
Thread thread = new Thread();
boolean running = true;
Random r = new Random();
public int randX = r.nextInt(400);
public int randY = r.nextInt(400);
public int randW = r.nextInt(100);
public int randH = r.nextInt(100);
public int randX2 = r.nextInt(400);
public int randY2= r.nextInt(400);
public int randW2 = r.nextInt(100);
public int randH2 = r.nextInt(100);
public void start(){thread.start();}
public void stop(){}
public void init(){
setSize(500,500);
Button randomButton = new Button("RANDOMNESS");
randomButton.addActionListener(this);
add(randomButton);
}
public void run(){}
public void destroy(){}
public void paint(Graphics g){ //paints rect with random with and height
g.fillRect(randX, randY, randW, randH);
g.fillRect(randX2, randY2, randW2, randH2);
}
@Override
public void actionPerformed(ActionEvent e) {// How can they repaint at a different random location after pressing the button?
System.out.println("WORKING");
}
}
答案 0 :(得分:2)
您只需在actionPerformed(...)
方法中更改randX,randY,....,就像您当前正在做的那样,给它们添加新的随机值,然后调用repaint()
来发信号通知小程序重绘自己?
除此之外,这段代码应该做什么?
Thread thread = new Thread();
// .....
public void start(){thread.start();}
根据我的观点,它没有做太多。