Hello again. I am working with canvas and attempting to fill the screen with an area of pixels, of which I can color through layered for loops seen below. My problem is that when targeting the pixels to color, my loops always seem to lead to a higher value than the size of my array.
The size of pixels is 48600 when printed out, but yet the index 48600 would be out of bounds... i.e. if it had an index of 48600 the size would be 48601.
Take a look and see if you notice anything... Any hints appreciated
Game.java
import java.awt.Canvas; 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; import audboy.project.graphics.View; public class Game extends Canvas implements Runnable { /** * */ private static final long serialVersionUID = 1L; public static int width = 300; public static int height = width / 16 * 9; public static int scale = 3; private boolean running = false; private View view; private JFrame jframe; private Thread thread; private BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); private int[] pixels = ((DataBufferInt)bi.getRaster().getDataBuffer()).getData(); public Game(){ Dimension size = new Dimension(width * scale, height * scale); setPreferredSize(size); view = new View(width, height); jframe = new JFrame(); } public synchronized void start(){ running = true; thread = new Thread(this, "Display Thread"); thread.start(); } public synchronized void stop(){ running = false; try { thread.join(); } catch (InterruptedException e){ e.printStackTrace(); } } public void run() { while(running){ tick(); render(); } } public void tick(){ } public void render(){ BufferStrategy bs = getBufferStrategy(); if(bs == null){ createBufferStrategy(3); return; } view.render(); for(int i = 0; i < pixels.length; i++){ pixels[i] = view.pixels[i]; } Graphics g = bs.getDrawGraphics(); g.drawImage(bi, 0, 0, null); g.dispose(); bs.show(); } public static void main(String[] args){ Game game = new Game(); game.jframe.setResizable(false); game.jframe.setTitle("Project"); game.jframe.add(game); game.jframe.pack(); game.jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); game.jframe.setLocationRelativeTo(null); game.jframe.setVisible(true); game.start(); } }
View.java
public class View { private int width, height; public int[] pixels; public View(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; y++){ pixels[x + y * width] = 0xff00ff; //hex pink } } } }
Error:Exception in thread "Display Thread" java.lang.ArrayIndexOutOfBoundsException: 48600
at audboy.project.graphics.View.render(View.java:17)
at audboy.project.Game.render(Game.java:76)
at audboy.project.Game.run(Game.java:61)
at java.lang.Thread.run(Thread.java:680)