Home Segments Top Top Previous Next

870: Mainline

The scaling computations required to adjust the arguments of drawImage are straightforward, albeit tedious:

import java.awt.*;
import javax.swing.*;
import java.util.*;
public class Poster extends JComponent implements PosterInterface {
 private String file;
 private Image image;
 public void setImageFile (String s) {
  if (s != file) {
   file = s;
   if (file == null) {image = null;}
   else {
    image = MovieAuxiliaries.readMovieImage (file);
   }
   repaint();
  }
 }
 public void paint(Graphics g) {
  if (image != null) {
   Dimension d = getSize();
   int x, y, width, height, border = 20;
   // Tedium begins                                     
   double imageRatio = (float) image.getHeight(this)    
                       / image.getWidth(this);          
   double windowRatio = (float) d.height / d.width;     
   if (imageRatio > windowRatio) {                      
    height = d.height - border;                         
    width = image.getWidth(this) * (d.height - border)  
            / image.getHeight(this);                    
   }                                                    
   else {                                               
    width = d.width - border;                           
    height = image.getHeight(this) * (d.width - border) 
             / image.getWidth(this);                    
   }                                                    
   x = (d.width - width) / 2;                           
   y = (d.height - height) / 2;                         
   // Tedium ends                                       
   g.drawImage(image, x, y, width, height, this); 
  } 
 } 
 public Dimension getMinimumSize() {return new Dimension(200, 300);} 
 public Dimension getPreferredSize() {return new Dimension(200, 300);} 
}