I have am writing a small game using Applet. I want to be able to check the color of a pixel on the screen. However, when I use .getRGB() on my buffered image in my game loop (a while loop that executes over and over), it gives me inconsistent values even if the pixel color never actually changes!
For example, if I fill the image with green color and I call .getRGB() on a pixel in the middle of the screen sometimes it gives me 0xFF00FF00 (green) as the color, other times it gives me 0xFF000000 (black) even if the color always stays green!
Any help?
Here’s the relevant code if that helps, I’ve minimized it just to focus on the problem:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
public class t extends Applet implements Runnable {
Graphics2D bufferG;
BufferedImage bufferI;
final int WIDTH = 500, HEIGHT = 500;
public void init() {
setSize(WIDTH, HEIGHT);
bufferI = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
bufferG = bufferI.createGraphics();
(new Thread(this)).start();
}
public void run() {
while (true){
if (bufferI.getRGB(WIDTH/2, HEIGHT/2)==0xFF000000) System.out.println("BLACK");
}
}
public void paint(Graphics g) {
bufferG.setColor(Color.green);
bufferG.fillRect(0, 0, WIDTH, HEIGHT);
g.drawImage(bufferI, 0, 0, this);
}
}
I’m not sure why you are dealing with buffers. This paints the image green & produces no output on the command line (reporting the color as black).
Notes
To compile & run
Size
The size of an applet is set in the HTML that loads it, it should not attempt to set its own size.