是否可以调整 Jlabel 的大小?

Is it possible to resize a Jlabel?

我想在鼠标进入包含图片的 JLabel 时调整图片大小。我知道如何调整图片大小,事实上,它现在可以工作了,但问题是 de JLabel 没有改变他的大小!

我试过: MyLabel.setSize(360,580); MyLabel.resize(360,580); MyLabel.setPreferredSize(360.580);

这三个选项都不会更改 JLabel 的大小。这是当前代码:

    private void don1MouseExited(java.awt.event.MouseEvent evt) {                                 
    don1.setSize(260,330);
    aux2 = new ImageIcon(aux.getImage().getScaledInstance(260, 330, Image.SCALE_DEFAULT)); //resize the image 
    don1.setIcon(aux2);
}

有什么帮助吗? 谢谢¡¡

你只需要在 JLabel 上设置图标,其余的只需要跟随即可,无需任何其他代码。

看这个例子:

import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestResizingLabel {

    protected void initUI() throws MalformedURLException {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        final ImageIcon originalImage = new ImageIcon(new URL(
                "http://mgl.skyrock.net/big.138643852.jpg?78138742"));
        final ImageIcon scaledImage = new ImageIcon(originalImage.getImage()
                .getScaledInstance(originalImage.getIconWidth() / 4,
                        originalImage.getIconHeight() / 4, Image.SCALE_SMOOTH));
        final JLabel label = new JLabel(scaledImage);
        label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                System.err.println("in");
                label.setIcon(originalImage);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                label.setIcon(scaledImage);
            }
        });
        panel.add(label);
        frame.add(panel);
        frame.setSize(600, 600);
        frame.setVisible(true);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new TestResizingLabel().initUI();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}