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

JPanel二维对象数组绘制异常:动态随机彩色盒子部分未显示问题排查

Fix for Missing Boxes in Your Java Swing Dynamic Grid

Hey there! Let's break down why some of your boxes aren't showing up and fix it step by step.

The Root Cause

Looking at your paintComponent method, there's a mix-up in how you map array indices to screen coordinates:

  • Your 2D array boxes[i][j] uses i for rows (vertical position) and j for columns (horizontal position)
  • But you're passing i * box_width as the X coordinate (horizontal) and j * box_heigt as the Y coordinate (vertical)

When your row count is smaller than your column count (like your 4-row, 5-column example), the j index goes up to 4. Multiplying that by box_heigt (which is panel height / 4) gives you a Y value equal to the full panel height—so those boxes get drawn outside the visible area of the panel.

Also, you have a typo: box_heigt should be box_height (small issue, but it's good to fix for readability).

The Fix

Update your paintComponent method to swap the coordinate mapping, and fix the typo:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Rectangle t = g.getClipBounds();
    int box_width = t.width / this.boxes[0].length;
    int box_height = t.height / this.boxes.length; // Fixed typo here
    for(int i = 0 ; i < this.boxes.length; i ++) {
        for(int j = 0 ; j < this.boxes[0].length; j++) {
            // Swap i and j for X/Y coordinates to match row/column logic
            boxes[i][j].draw(j * box_width, i * box_height, box_width, box_height, g);
        }
    }
}

Why This Works

  • j * box_width: Column index j maps to horizontal (X) position—each column shifts right by one box width
  • i * box_height: Row index i maps to vertical (Y) position—each row shifts down by one box height

This ensures every box is drawn within the bounds of your panel, no matter how many rows/columns you use.

Quick Test Tip

Try creating a grid with more rows than columns (e.g., new CustomPanel(5,4)) after fixing the code—you'll see all boxes render correctly now.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 20:44:04