JPanel二维对象数组绘制异常:动态随机彩色盒子部分未显示问题排查
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]usesifor rows (vertical position) andjfor columns (horizontal position) - But you're passing
i * box_widthas the X coordinate (horizontal) andj * box_heigtas 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 indexjmaps to horizontal (X) position—each column shifts right by one box widthi * box_height: Row indeximaps 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

