Swing - ImageIcon.paintIcon() problems with scaled Graphics
When calling the ImageIcon.paintIcon() method with a significantly scaled down Graphics object I'm observing problems - specifically drawing junk outside the region of the scaled down icon.
I can reproduce this behavior with the following program. You'll need to create your own icon named "mycon.gif" (try something around 100x100 pixels) and keep rotating the mouse wheel til the icon size is vanishingly small.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclass Problemextends JFrame{
public Problem(String name){
super(name);
add(new ProblemPanel(), BorderLayout.CENTER);
}
privatestaticvoid createGui(){
Problem p =new Problem("Problem");
p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p.setSize(800, 800);
p.setVisible(true);
}
publicstaticvoid main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
publicvoid run(){
createGui();
}
});
}
}
class ProblemPanelextends JPanelimplements MouseWheelListener{
privatestaticfinal String ICON ="mycon.gif";
privatestaticfinaldouble FACTOR = 1.1;
private Icon icon;
privatedouble scale;
public ProblemPanel(){
this.icon =new ImageIcon(getClass().getResource(ICON));
this.scale = 1.0;
addMouseWheelListener(this);
}
publicvoid mouseWheelMoved(MouseWheelEvent event){
if (event.getWheelRotation() < 0){
this.scale *= FACTOR;
}
else{
this.scale /= FACTOR;
}
repaint();
}
publicvoid paint(Graphics g){
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.white);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.scale(this.scale, this.scale);
this.icon.paintIcon(this, g2d, 100, 100);
}
}

