我目前正在嘗試將像素繪製到我的窗口,並且我似乎在程序啓動時遇到了索引超出界限的錯誤。我真的不知道如何解決它。有人可以告訴我問題在哪裏嗎?我已經檢查了很多次,但似乎應該對我很好。我在下面給出了我的項目的所有代碼,但錯誤發生在for循環所在的render方法(Game類)中。數組索引超出邊界繪製像素
編輯:
的錯誤是什麼地方在遊戲中的類環。它說
java.lang.ArrayIndexOutOfBoundsException:48601" 的線 「pixles [I] = screen.pixels [I]」
Screen類
public class Screen {
private int width,height;
public int[] pixels;
public Screen(int width,int height){
this.width = width;
this.height = height;
pixels = new int[width * height];
}
public void render(){
for (int y = 0; y < height; y++){
for (int x = 0; x < width; x++){
pixels[x + y * width] = 0xff00ff;
}
}
}
}
Game Class
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable{
private int width = 300;
private int height = width/16 * 9;
private int scale = 3;
private Thread thread;
private boolean running = false;
private JFrame frame;
private BufferedImage image = new BufferedImage(width * scale, height * scale,BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
private Screen screen;
public Game(){
screen = new Screen(width,height);
frame = new JFrame("Relm Of The Mad God Clone");
this.setPreferredSize(new Dimension(width * scale, height * scale));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(this);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
start();
}
public synchronized void start(){
thread = new Thread(this,"Running Thread");
thread.start();
running = true;
}
public synchronized void stop(){
try{
thread.join();
running = false;
}catch (InterruptedException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
Game g = new Game();
}
private void update(){
}
private void render(){
BufferStrategy buffer = getBufferStrategy();
if (buffer == null){
createBufferStrategy(3);
return;
}
screen.render();
for (int i = 0; i < pixels.length; i++){
pixels[i] = screen.pixels[i];
}
Graphics g = buffer.getDrawGraphics();
g.drawImage(image, 0, 0, getWidth(), getHeight(),this);
g.dispose();
buffer.show();
}
@Override
public void run() {
while (running){
update();
render();
}
}
}
準確的代碼在哪裏? – MadProgrammer
它在原始文章中說過,但它在Game類的for循環中處於某個位置。它說: 「java.lang.ArrayIndexOutOfBoundsException:48601」 在線 「pixles [I] = screen.pixels [I]」 @MadProgrammer – user2318396
執行兩個陣列具有相同的長度?添加一個println(),打印出每個的長度,以便您可以看到。 – NormR