Elias
Elias

Reputation: 1

Trying to paint after pressing a button

How can i make it repaint after pressing the button? When i start the applet up it paints 2 rects at random positions with random widths and heights, how can i get them to "respawn" at a different location after pressing the button?

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

    }

}

Upvotes: 0

Views: 128

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

How about you simply change randX, randY,.... within your actionPerformed(...) method by giving them new random values, just as you're currently doing, and then call repaint() to signal the applet to repaint itself?


Just as an aside, what is this code supposed to be doing?

Thread thread = new Thread();

// .....

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

Per my view, it's not doing much.

Upvotes: 2

Related Questions