import java.applet.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.util.*; import java.lang.*; // use the old event model to be compatible with Java 1.1.5 public class PixelView extends Applet implements AdjustmentListener { Label label; Scrollbar scrollbar; Image image; String param; int imageHeight, imageWidth; int appletHeight, appletWidth; int imageLoadLine; public void init() { appletHeight = getHeight(); appletWidth = getWidth(); String imageFilename = getParameter("filename"); if (imageFilename == null) imageFilename = getParameter("image"); image = loadImage(imageFilename); imageHeight = image.getHeight(this); imageWidth = image.getWidth(this); System.out.println("#### For image "+imageFilename+" width="+ imageWidth+" height="+imageHeight); String res = getParameter("starting_pixels"); int npix = 50; if (res != null) { npix = Integer.parseInt(res); } // orientation, initial value, size of bubble, minimum, maximum scrollbar = new Scrollbar(Scrollbar.HORIZONTAL, npix, 10, 2, imageWidth+10); scrollbar.addAdjustmentListener(this); label = new Label("Number of pixels in image = "+imageWidth+" x "+imageHeight+" = "+(imageWidth * imageHeight)); setLayout(null); add(scrollbar); add(label); validate(); Dimension dim = scrollbar.getPreferredSize(); Dimension dimlab = label.getPreferredSize(); int swid = 200; int wid = swid + dimlab.width+20; if (wid > appletWidth) { swid = appletWidth - dimlab.width - 25; wid = swid + dimlab.width + 20; } int widloc = appletWidth/2 - wid/2; if (widloc < 0) widloc = 0; scrollbar.setBounds(widloc,5,200,dim.height); label.setBounds(widloc+220,5,dimlab.width,dimlab.height); imageLoadLine = 10+(dim.height > dimlab.height ? dim.height : dimlab.height); repaint(); } public void update(Graphics g) { paint(g); } public void paint(Graphics g) { Image buffer = createImage(appletWidth, appletHeight); Graphics gb = buffer.getGraphics(); int n = scrollbar.getValue(); label.setText("Number of pixels in image = "+n+" x "+n+" = "+(n*n)); Image subimage = createImage(n,n); Graphics gs = subimage.getGraphics(); gs.drawImage(image,0,0,n,n,0,0,imageWidth,imageHeight,this); gb.drawImage(subimage,0,0,imageWidth,imageHeight,0,0,n,n,this); g.drawImage(buffer,0,imageLoadLine,this); buffer.flush(); gb.dispose(); subimage.flush(); gs.dispose(); } // Listeners public void adjustmentValueChanged(AdjustmentEvent e) { if (e.getSource() == scrollbar) { repaint(); } } // Utilities for getting images and audio clips from JAR or URL public Image loadImage(String name) { // first try the URL Image img = null; URL u = getClass().getResource( (String) name); if (u == null) { u = getDocumentBase(); img = getImage(u,name); } else { img = getImage(u); } MediaTracker mt = new MediaTracker(this); mt.addImage(img, 0); try { mt.waitForAll(); } catch ( Exception ex ) {img = null; } return img; } }