|
image download from server
I am aware of the Sun article page "How to Use Icons", but I do not understand it fully. The advanced Sun texts are informative but not instructive to me.
So here is what I did for the moment, in order to test what is really going on. I divided the Image loading part form the image displaying part, by triggering the download and the image paint under two different buttons (first button downloads the file and second button paints the image).
I found out that it takes very long to get the image (of an average size of 40 kb) from the server (takes several seconds) and after downloading it, it seams still not ready to paint because I get erros according the image size… (can not get size, see try and catch).
I am just trying to understand how things work. From the first button on the image should be stored under the var image or....
So ones image points to the photo I should be able to get the size through image.getWidth(null); ......
Why is that still not working?
here is part of the code
private class EventHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
// images are download before display
if (evt.getSource() == firstButton) {
count++;
if (count==maxcount)
count=0;
image = downloadImage(img[count].name); // the download
}
if (evt.getSource() == nextButton) // display image
try {
imgwidth = image.getWidth(null);
}
catch (Exception e) {
System.out.println("can not get image width " + imgwidth);
//e.printStackTrace();
}
try {
imgheight = image.getHeight(null);
}
catch (Exception e) {
System.out.println("can not get image height " + imgheight);
//e.printStackTrace();
}
x = (int)(framew - imgwidth)/2; // centre the image on the window
y = (int)(frameh - imgheight)/2;
displayPanel.repaint();
}
}
}
private Image downloadImage(String filename) { // the image file reader
Image images=null;
URL url;
url = getClass().getResource("Imagestore/" + filename);
try {
images = ImageIO.read(url);
} catch (IOException ex) {
System.out.println("can not read the file: " + filename);
ex.printStackTrace();
}
return images;
}
private class ImageDisplay extends JPanel { // Defines the display panel.
public void paintComponent(Graphics g) { // for painting the images
this.setBackground(Color.WHITE);
super.paintComponent(g);
g.drawImage(image,x, y, imgwidth, imgheight,this);
// the image infotext
textLabel.setBounds(img[count].textx,img[count].texty, 300 , 50);
// color, position of the tet
settextColor(img[count].textcolor);
textLabel.setText(img[count].info);
}
}
|