是否可以调整Jlabel的大小?

时间:2015-02-10 20:45:22

标签: java image swing resize jlabel

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

我试过了:      MyLabel.setSize(360580);      MyLabel.resize(360580);      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);
}

有任何帮助吗? Thanks¡¡

1 个答案:

答案 0 :(得分:7)

您只需在JLabel上设置图标,其余部分应该在没有任何其他代码的情况下进行。

见这个例子:

Demo picture

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

}