简体   繁体   English

按下按钮后尝试绘画

[英]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? 当我启动小程序时,它会在宽度和高度随机的任意位置绘制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");

    }

}

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? 怎么样,只需在actionPerformed(...)方法中更改randX,randY .....的方式即可,就像现在一样,给它们提供新的随机值,然后调用repaint()来通知小程序重新绘制自身?


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. 根据我的观点,它做的并不多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM