按下按钮后如何重新粉刷?当我启动小程序时,它会在宽度和高度随机的任意位置绘制2个矩形,按下按钮后如何使它们在不同的位置“重生”?

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

    }

}

最佳答案

您如何通过给它们新的随机值(就像您当前正在执行的操作一样)在actionPerformed(...)方法中更改randX,randY,....,然后调用repaint()来通知applet自己重新绘制呢?



顺便说一句,这段代码应该做什么?

Thread thread = new Thread();

// .....

public void start(){thread.start();}


根据我的观点,它做的并不多。

09-13 12:34