Question

I need a UI where i want to depict a network device's graphical representation in swing. For this, i am just loading multiple images and overlap them one by one to show the current state of the device. I have to support zooming for this view. The zoom code looks like this.

public void zoom(double factor){
    if (factor < MIN_ZOOM_VALUE)
        factor = MIN_ZOOM_VALUE;
    else if (factor > MAX_ZOOM_VALUE)
        factor = MAX_ZOOM_VALUE;

    scaleFactor = factor;

    layeredPane.revalidate();
    layeredPane.repaint();
}

The images are added as labels.

private class ImageLabel extends JLabel{

    private ImageIcon image;
    private Position position;

    public ImageLabel(ImageIcon image, Position position){
        super(image);
        this.image = image;
        this.position = position;
    }

    public void paintComponent(Graphics g) {

        int newX = (int)(position.getLeft() * scaleFactor);
        int newY = (int)(position.getTop() * scaleFactor);

        Graphics2D g2 = (Graphics2D)g;
        int newW = (int)(position.getWidth() * scaleFactor);
        int newH = (int)(position.getHeight() * scaleFactor);

        setBounds(newX, newY, newW, newH);

        g2.setRenderingHint(
                     //RenderingHints.KEY_INTERPOLATION,
                    //RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                RenderingHints.KEY_ANTIALIASING, 
                        RenderingHints.VALUE_ANTIALIAS_ON);
        g2.drawImage(image.getImage(), 0, 0, newW, newH, null);

    }
}

But the problem here is, when i zoom in once and zoom out, some of the images disappear. Any idea why it behaves like this?

Was it helpful?

Solution

+1 to @AndrewThompsons comment.

The only other problem I can see is you dont honor the paint chain.

Also always remember to honor the paint chain by calling super.XXX implementation of overriden paint methods (and for that matter any overriden method), unless you know what you are doing and are purposely not calling their supers implementation, or else visual artifacts like the ones you describe could/will happen.

To do this you would call super.paintComponent(Graphics g) as the first method in overridden paintComponent like so:

@Override
protected void paintComponent(Graphics g) {
     super.paintComponent(g);

     //do other drawings here
}

Also note how I use @Override annotation so that I am sure I am overriding the correct method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top