paintComponent 内部函数

paintComponent inside function

我是一个初学者,所以我认为我犯了一个愚蠢的错误,但我有:

public class Draw extends JPanel {

    private static final long serialVersionUID = 1L;

    public Draw(int rx, int ry)
    {

        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            this.setBackground(Color.WHITE);
            g.setColor(Color.BLUE);
            try{
                g.fillRect(rx, ry, 5, 5);
                Thread.sleep(1000);
            }
            catch(InterruptedException ex)
            {
                Thread.currentThread().interrupt();
            }

        }
    }

    public static void main(String[] args) {
        JFrame f = new JFrame("Title");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        for (int i = 1; i < 40; i++) {
            Random r = new Random();
            int rx = r.nextInt(40);
            int ry = r.nextInt(40);

            Draw d = new Draw(rx, ry);
            f.add(d);
            f.setSize(400, 400);
            f.setVisible(true);
        }
    }
}

我希望代码在随机位置生成矩形,并在每个循环中有一些延迟。 Java 正在写 "void is an invalid type for the variable paintComponent"。我不相信这一点,因为如果我将 paintComponent 放在 Draw 函数之外它就可以工作(但不是我希望他工作的那样)。 paintComponent 是不是不能在其他函数里面或者有其他错误?

这是您想要的示例:

您不应在其他方法(例如构造函数)中定义方法。如果只需要创建间隔,也不要使用线程。请改用 javax.swing.Timer

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Draw extends JPanel {

    private static final int FRAME_HEIGHT = 400;

    private static final int FRAME_WIDTH = 400;

    private static final int RECT_WIDTH = 40;

    private static final int RECT_HEIGHT = 25;


    private static final long serialVersionUID = 1L;

    public Draw()
    {
        this.setBackground(Color.WHITE);
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        //
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.BLUE);

        Random r = new Random();
        int rx = r.nextInt(FRAME_WIDTH-RECT_WIDTH);
        int ry = r.nextInt(FRAME_HEIGHT-RECT_HEIGHT);
        g.fillRect(rx, ry, RECT_WIDTH, RECT_HEIGHT);
    }

    public static void main(String[] args) {
        JFrame f = new JFrame("Title");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final Draw d = new Draw();
        f.add(d);
        f.setSize(FRAME_WIDTH, FRAME_HEIGHT);
        f.setVisible(true);

        Timer t = new Timer(1000, new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                d.repaint();
            }
        });
        t.start();
    }
}

祝你好运。