我在java中有一个问题:我在一个绘制图像的类中有一个方法。 编辑:改变了||和&&'s,修复了其他,但现在图像是红色的。 顺便说一句:假设已经定义了网格。
public BufferedImage scene() {
BufferedImage image = new BufferedImage(250, 250, BufferedImage.TYPE_INT_RGB);
if (ready) {
int tv=0;
int tc=0;
for (int x = 0; x < 250; x++) {
for (int y = 0; y < 250; y++) {
int px = (int) ((x + r) / 16);
int py = (int) (y / 16);
if (px >= 0 && py >= 0 && px < width && py < height) {
image.setRGB(x, y, grid[px][py].image.getRGB(
(x + r) % 16, (y) % 16));
} else {
image.setRGB(x, y, 0xFF0000);
}
}
}
}
return image;
}
但是当我运行代码时,我得到了:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 19
at general.Level.scene(Level.java:47)
at general.Game.paintComponent(Game.java:34)
at javax.swing.JComponent.paint(JComponent.java:1037)
at javax.swing.JComponent._paintImmediately(JComponent.java:5106)
at javax.swing.JComponent.paintImmediately(JComponent.java:4890)
at javax.swing.RepaintManager$3.run(RepaintManager.java:814)
at javax.swing.RepaintManager$3.run(RepaintManager.java:802)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:802)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:745)
at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:725)
at javax.swing.RepaintManager.access$1000(RepaintManager.java:46)
at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1684)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:708)
at java.awt.EventQueue.access$400(EventQueue.java:82)
at java.awt.EventQueue$2.run(EventQueue.java:669)
at java.awt.EventQueue$2.run(EventQueue.java:667)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:678)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException
答案 0 :(得分:1)
注意:自从我写这个答案以来,这个问题已被编辑。
这项检查似乎有误:
if (px >= 0 || py >= 0 || px < width || py < height)
您需要逻辑AND(&&
)而非OR(||
),否则可能会通过px
或py
的无效值。这可能是导致数组索引错误的原因(尽管您没有共享足够的代码来确定这一点)。