1

Consider this small runnable example:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test2 extends JFrame implements MouseWheelListener{
        ArrayList<JLabel> lista = new ArrayList<JLabel>();
        JPanel p;
        double d = 0.1;
        Test2(){
        p=new JPanel();
        _JLabel j = new _JLabel("Hello");
        j.setOpaque(true);
        j.setBackground(Color.yellow);
        p.add(j);
        p.setBackground(Color.blue);
        add(p);
        this.setVisible(true);
        this.setSize(400,400);
        addMouseWheelListener(this);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    public static void main(String args[]){
        new Test2();
    }
    private class _JLabel extends JLabel{

        _JLabel(String s){
            super(s);
        }

        protected void paintComponent(Graphics g) {
            d+=0.01;
            Graphics2D g2d = (Graphics2D) g;
            g2d.scale(d, d);
            setMaximumSize(null);
            setPreferredSize(null);
            setMinimumSize(null);
            super.paintComponent(g2d);
            System.out.println("d= " +d);
        }
    }
    public void mouseWheelMoved(MouseWheelEvent e) {
            this.repaint();
    }

}

When I scroll the mousewheel the JLabel increases in size and the variable d is printed out. However, when it reaches the actual size (d=1) only the text continues zooming. How can I make the background continue to zoom?

user1506145
  • 5,176
  • 11
  • 46
  • 75

1 Answers1

2

You shouldn't be modifying the preferred/min/max sizes in the paint method, this coud have unexpected results (cause another repaint).

The problem is that the parent layout has no reference from which to determine size of the component. That is, the preferred/in/max size is actually calculated based on the font information & this information is not been changed.

So, while it "appears" that the component is being resized, it's actual size has not changed.

Try instead to scale against the original font size.

AffineTransformation af = AffineTranfrmation.getScaleInstance(scale, scale);
Font font = originalFont.deriveFont(af);
setFont(font);

invalidate();
repaint();

Of course you run into the problem of what happens if the user changes the font, but with a little bit of flagging, you should be able to over come that

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366