Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

ImageIcon.paintIcon() problems with scaled Graphics

843805Mar 29 2007 — edited Apr 2 2007
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.*;

public class Problem extends JFrame {
    
    public Problem(String name) {
        super(name);
        add(new ProblemPanel(), BorderLayout.CENTER);
    }
    
    private static void createGui() {
        Problem p = new Problem("Problem");
        p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        p.setSize(800, 800);
        p.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createGui();
            }
        });
    }
}

class ProblemPanel extends JPanel implements MouseWheelListener {
    private static final String ICON = "mycon.gif";
    private static final double FACTOR = 1.1;
    
    private Icon icon;
    private double scale;
    
    public ProblemPanel() {
        this.icon = new ImageIcon(getClass().getResource(ICON));
        this.scale = 1.0;
        addMouseWheelListener(this);
    }
    
    public void mouseWheelMoved(MouseWheelEvent event) {
        if (event.getWheelRotation() < 0) {
            this.scale *= FACTOR;
        }
        else {
            this.scale /= FACTOR;
        }
        repaint();
    }
    
    public void 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);
    }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 30 2007
Added on Mar 29 2007
7 comments
227 views