-
Enhancement
-
Resolution: Unresolved
-
P5
-
None
-
1.4.1
-
x86
-
windows_2000
Name: jk109818 Date: 02/04/2003
FULL PRODUCT VERSION :
java version "1.4.1_01"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1_01-b01)
Java HotSpot(TM) Client VM (build 1.4.1_01-b01, mixed mode)
FULL OPERATING SYSTEM VERSION :
Windows 2000 SP2
A DESCRIPTION OF THE PROBLEM :
There is no good way of displaying and resizing images
built into a java swing component. This seems to be
something people would use quite often. I am submitting
some source code that takes an image as a parameter. A
programmer can simply create the component and the image
will be resized to the components size.
REPRODUCIBILITY :
This bug can be reproduced always.
---------- BEGIN SOURCE ----------
import java.awt.*;
import javax.swing.JPanel;
public class ImagePanel extends JPanel {
private Image image;
private Insets insets = new Insets(0, 0, 0, 0);
public ImagePanel() {
}
public ImagePanel(Image image) {
this.image = image;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
revalidate();
}
public Dimension getPreferredSize() {
getInsets(insets);
int w = insets.left + insets.right;
int h = insets.top + insets.bottom;
if (image != null) {
w += image.getWidth(null);
h += image.getHeight(null);
}
Dimension sz = new Dimension(w, h);
return sz;
}
public Dimension getMinimumSize() {
return getPreferredSize();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Image tempImage = null;
if (image == null) {
return;
}
getInsets(insets);
tempImage = // Needs to be a temporary image or each repaint
image.getScaledInstance( //will cause image degradation
this.getWidth(),
this.getHeight(),
Image.SCALE_FAST);
// The getScaledInstance will continue before the image is drawn
// so we need to wait for it to be created or the method
// will be called over and over and over and...
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(tempImage, 0); // Image to track
try {
tracker.waitForID(0);
} catch (InterruptedException e) {
System.out.println(e); // Exception...
return; // bail
}
int w = this.getWidth() - insets.left - insets.right;
int h = this.getHeight() - insets.top - insets.bottom;
//clip in case image exceeds wxh
Graphics g2 =
(Graphics) g.create(
insets.left,
insets.top,
this.getWidth(),
this.getHeight());
int x = (w - tempImage.getWidth(null)) / 2;
int y = (h - tempImage.getHeight(null)) / 2;
g2.drawImage(tempImage, x, y, this);
g2.dispose();
this.setSize(tempImage.getWidth(null), tempImage.getHeight
(null));
}
}
---------- END SOURCE ----------
(Review ID: 180841)
======================================================================