You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

图形循环问题:图形生成存在Bug

解决只显示1个随机矩形的问题

嘿,我看你遇到的问题啦——想画10个位置和大小都随机的矩形,但目前只出来1个,这事儿我熟!咱们先拆解问题,再给你把代码改对~

常见问题原因

你大概率是踩了这几个Swing绘制的坑:

  • 没在paintComponent里写循环,只执行了一次绘制代码
  • 随机生成的坐标/大小超出了面板可视范围,导致其他矩形“隐身”了
  • 忘了调用super.paintComponent(g),导致绘制内容被覆盖

修正后的完整代码

我给你写了完整可运行的代码,每一步都加了注释:

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Punto1 extends JPanel {

    public static void main(String[] args) {
        System.out.println("Estoy en el main");
        JFrame frame = new JFrame("10个随机矩形");
        Punto1 panel = new Punto1();
        frame.add(panel);
        frame.setSize(800, 600); // 给矩形足够的显示空间
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g); // 必须调用!清空面板,准备新绘制
        
        // 循环10次,每次画一个随机矩形
        for (int i = 0; i < 10; i++) {
            // 生成在面板范围内的随机坐标:避免矩形超出窗口
            int x = (int) (Math.random() * (getWidth() - 50));
            int y = (int) (Math.random() * (getHeight() - 50));
            // 生成20-50之间的随机宽高
            int width = 20 + (int) (Math.random() * 30);
            int height = 20 + (int) (Math.random() * 30);
            
            // 给每个矩形加随机颜色,更容易区分
            Color randomColor = new Color((float)Math.random(), (float)Math.random(), (float)Math.random());
            g.setColor(randomColor);
            g.fillRect(x, y, width, height); // 填充矩形,比描边更明显
            // 要是想描边可以用:g.drawRect(x, y, width, height);
        }
    }
}

关键知识点说明

  1. 必须重写paintComponent:Swing的自定义绘制都要在这个方法里做,这是绘制的入口
  2. super.paintComponent(g)不能丢:它负责清除上一次的绘制内容,处理背景色,不然新画的矩形会和旧的重叠,甚至显示异常
  3. 控制随机范围:用getWidth()和getHeight()获取面板的实际大小,让矩形坐标和大小都落在面板范围内,避免“隐身”
  4. 循环绘制:通过for循环执行10次绘制逻辑,才能画出10个矩形

额外优化小技巧

如果想让矩形更有辨识度,可以给每个矩形加随机颜色,就像代码里那样——用new Color(float, float, float)生成RGB随机颜色,效果很直观~

内容的提问来源于stack exchange,提问作者carlos puello

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:19:17