Not using repaint() correctly?
Hello - I have a class which I have created which makes a window and then attempts to load a greyscale image into it. The image loads correctly if it is painted before the pane is displayed, but not after. The final application is going to have a button to press to display the image, so I need to load the image after the rest of the frame is displayed (and overwrite what image is already on the screen)
Because it is displaying correctly at first, I think I don't understand how repaint() works... any advice is helpful, code follows:
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.*;
import java.io.*;
publicclass Main
{
privatestatic ImageIcon icon;
privatestatic BufferedImage buffImage;
privatestatic Graphics g;
privatestatic JLabel image;
privatestatic JFrame frame;
publicstaticvoid main(String [] args)
{
frame =new JFrame();
frame.setSize(640, 480);
frame.setLocation(300, 300);
icon =new ImageIcon("blank.gif");
Image img = icon.getImage();
buffImage =new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
g = buffImage.getGraphics();
g.drawImage(img, 0, 0,null);
image =new JLabel(icon);
//setImage();//if called here - it loads the image
frame.getContentPane().add(image,"Center");
//setImage();//if called here - it loads the image
frame.setVisible(true);
setImage();//if called here - it is blank.gif
}
publicstaticvoid setImage()
{
finalint WIDTH = 162;
finalint HEIGHT = 128;
int x = 0;
int y = 0;
byte[] data =newbyte[WIDTH*HEIGHT*2];
try
{
System.out.println("Start");
FileInputStream stream =new FileInputStream("Patient000_2007-01-03_14-11-30_IM_1.raw");
stream.read(data);
for(int i=0; i<data.length/2; i++)
{
if(x>=WIDTH*2)
{
x=0;
y=y+2;
}
int value = 255-((byte)data[(i*2)] & 0xff);
g.setColor(new Color(value, value, value));
g.fillRect(x, y, 2, 2);
x=x+2;
}
//this is where I think I am messing up.
image =new JLabel(new ImageIcon(buffImage));
image.revalidate();
image.repaint();
frame.repaint();
frame.getContentPane().remove(image);
frame.getContentPane().add(image,"Center");
System.out.println("Done");
}catch(Exception e)
{
e.printStackTrace();
}
}
}

