In the code below I convert a 2dim array to a buffered image (which works, the image is binary (back and white)). Then I display this image.
My question now is how can I update this image (because I want to draw something in every run of a loop which is not displayed here).
This also brings me to my second question: how can I draw a point on this image. (This also means that if I want to draw a point on 150,100 ; it should be on pixel 150,100 of the image).
public void showImage(int xPoint, int yPoint) throws IOException {
// Two dim array conversion to a bufferedImage
BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < width; y++) {
for (int x = 0; x < height; x++) {
tempValue = (pixelArray[y][x]==1) ? 255 : 0;
int value = tempValue << 16 | tempValue << 8 | tempValue;
bimg.setRGB(x, y, value);
}
}
JFrame canvas = new JFrame();
canvas.setSize(bimg.getWidth(), bimg.getHeight());
canvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas.setTitle("Contour");
Container pane = canvas.getContentPane();
ColorPanel panel = new ColorPanel(bimg,xPoint,yPoint);
pane.add(panel);
canvas.setVisible(true);
}
and
class ColorPanel extends JPanel {
BufferedImage bimg;
int x;
int y;
public ColorPanel(BufferedImage image,int _x, int _y) {
bimg = image;
x = _x;
y = _y;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(bimg, null, 0, 0);
}
}
what I tried was:
g2d.setColor(Color.RED);
g2d.drawLine(x, y, x, y);
Though a new window opened on every run and I don’t think the point was on the right
I did a small example for you.
Basically it is a
JFramewith a customJPanelcalledColorPanel(which is much like yours with a few extra methods namelydrawDot(..)andsetBufferedImage(..))The
JFramewill initialize and add theJPanelwith anBufferedImage(completely black in this case). Thereafter white dots/pixels will be drawn on theImageat random co-ordinates (within the images bounds) every 2 seconds usingBufferedImage#setRGB(...).I set the timer to faster (200milis) and this is what the picture begins to look like:
NB its accurate, make it color an obvious co-ordinate like
drawPoint(0,0)and you will see ( i did not demonstrate this as a screenshot would than not be possible or of any use)Hope this helps.