Home » Java Basics » 07 - A Simple GUI Application with Thread Management
7

The Custom ImagePanel Component

How the component that holds the image is implemented

The component that holds the image is implemented by means of an inner class within ShowFruits. This ImagePanel class is a subclass of JPanel, a generic swing container that may hold any number of components. The inner class has a single property - an image. The class contains a 'setter' method that may be used to change the image property to a new java.awt.Image object. The paintComponent(graphics g) method is called when repaint() is invoked for this component (the paint() method invokes paintComponent internally). The method override causes the next fruit's image to be rendered on the component through g.drawImage(). The arguments of the function are the image object, the point on the component from which to commence rendering the picture (0,0 here), and the container on which the image should be drawn ('this' refers to the ImagePanel object). When paint(Graphics g) and related methods are overridden, super.paint() should always be invoked first to render the background of the component (super here refers to JPanel, the super class of ImagePanel)

 class ImagePanel extends JPanel {
Image image;
 
public void setImage(Image image) {
this.image = image;
}
 
public void paintComponent(Graphics g) {
System.out.println("Paint Runs on: " + Thread.currentThread().getName());
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}

The following code initializes the ImagePanel component in ShowFruits. The Toolkit class's static getDefaultToolkit() and getImage() functions are used to get the image file whose name is held in the image property of the appropriate element (currSlide=0 in init(); this corresponds to the first element) in the ArrayList that holds the fruits (imagePath is obtained from the first line of the input file). An instance of the imagePanel variable was created at the very beginning of the ShowFruits class; its size is set to 200 by 200 pixels (the images should conform to this size) and the setImage function is used to initialize the imagePanel's content.

  Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image = toolkit.getImage(this.imagePath  + "\\" +
myFruits.get(currSlide).image);
slideSize = new Dimension(200, 200);
imagePanel.setPreferredSize(slideSize);
imagePanel.setMinimumSize(slideSize);
imagePanel.setImage(image);