1

考虑这个小的可运行示例:

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();
    }

}

当我滚动鼠标滚轮时,JLabel 的大小会增加,并且会打印出变量 d。但是,当它达到实际大小 (d=1) 时,只有文本继续缩放。如何让背景继续放大?

4

1 回答 1

2

您不应该在绘制方法中修改首选/最小/最大尺寸,这可能会产生意想不到的结果(导致再次重新绘制)。

问题是父布局没有参考来确定组件的大小。也就是说,preferred/in/max size 实际上是根据字体信息计算出来的,并且这个信息没有改变。

因此,虽然“看起来”组件正在调整大小,但它的实际大小并没有改变。

尝试按原始字体大小进行缩放。

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

invalidate();
repaint();

当然你会遇到如果用户改变字体会发生什么的问题,但是通过一点标记,你应该能够克服这个问题

于 2012-07-18T14:24:11.003 回答