Page 189 - The Definitive Guide to Building Java Robots
P. 189
Preston_5564C06.fm Page 170 Friday, September 23, 2005 5:13 AM
170 CHAPTER 6 ■ VISION
We’re now ready to extend this object to create an image viewer.
Code Objective
The objective here is to extend SimpleSwing to create an image viewer.
Code Discussion
Before I put the image inside the white area above, I want to create a new object that will help
me with refreshing an image from a webcam later in the chapter. This new object will extend
JPanel and will just contain the image that is set into it. Also, as soon as the image gets set, it will
force a repaint of itself.
The fields in the class are an Image. There are two constructors: one with a default size of
320×240 and another allowing for the parameters of width (w) and height (h). See Example 6-4.
Example 6-4. ImagePanel.java
package com.scottpreston.javarobot.chapter6;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
public class ImagePanel extends JPanel {
public Image image = null;
public ImagePanel(){
init(320,240);
}
public ImagePanel(int w,int h) {
init(w,h);
}
private void init(int w,int h) {
setSize(w, h);
setMinimumSize(new Dimension(w, h));
setMaximumSize(new Dimension(w, h));
}
public void setImage(Image img) {
image = img;
repaint();
}