调整图标大小以适应 Java 中的 JButton?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25798156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:10:22  来源:igfitidea点击:

Resizing icon to fit on JButton in Java?

javaswingiconsjbutton

提问by Arman

Whenever I set an icon for my JButton it is always not sized correctly. How can I resize the icon to fit the button fully?

每当我为 JButton 设置图标时,它的大小总是不正确。如何调整图标大小以完全适合按钮?

final JButton btnSanic = new JButton();
Image img = icon.getImage();
Image newimg = img.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH);
icon = new ImageIcon(newimg);  
btnSanic.setIcon(icon);

采纳答案by MadProgrammer

There are any number of issues. To start with, all Swing components DON'T auto scale images. Sure, might be a nice idea, but given the amount of time and processing required to do it efficiently, I understand why they don't, so you need to do all the work...

有很多问题。首先,所有 Swing 组件都不会自动缩放图像。当然,这可能是一个不错的主意,但考虑到有效执行所需的时间和处理量,我理解他们为什么不这样做,因此您需要完成所有工作......

You should also remember, that the size of a component is not determined until it is laid out, and while you can provide all the sizing hints you might like, the layout manager is well within its rights to ignore one or more of these hints.

您还应该记住,组件的大小在布局之前不会确定,虽然您可以提供您可能喜欢的所有大小提示,但布局管理器完全有权忽略这些提示中的一个或多个。

Instead of "hoping" you know the size of the button, you should make use of the ComponentListenerAPI to receive notifications of when the component is actually resized...

与其“希望”知道按钮的大小,不如使用ComponentListenerAPI 来接收有关组件实际调整大小的通知...

Auto resizable icon

自动调整大小图标

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestButton {

    public static void main(String[] args) {
        new TestButton();
    }

    private BufferedImage master;

    public TestButton() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                try {
                    master = ImageIO.read(new File("C:\svg\Revert 256x256.png"));

                    JButton btn = new JButton() {

                        @Override
                        public Dimension getPreferredSize() {
                            return new Dimension(90, 50);
                        }

                    };
                    btn.addComponentListener(new ComponentAdapter() {

                        @Override
                        public void componentResized(ComponentEvent e) {
                            JButton btn = (JButton) e.getComponent();
                            Dimension size = btn.getSize();
                            Insets insets = btn.getInsets();
                            size.width -= insets.left + insets.right;
                            size.height -= insets.top + insets.bottom;
                            if (size.width > size.height) {
                                size.width = -1;
                            } else {
                                size.height = -1;
                            }
                            Image scaled = master.getScaledInstance(size.width, size.height, java.awt.Image.SCALE_SMOOTH);
                            btn.setIcon(new ImageIcon(scaled));
                        }

                    });

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(btn);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException exp) {
                    exp.printStackTrace();
                }
            }
        });
    }

}

Note: This example is far from optimised, but simply provides a broad concept of a possible solution...

注意:这个例子远非优化,只是提供了一个可能的解决方案的广泛概念......

Now, a word of warning. Image#getScaledInstanceis neither the fastest or greatest of scaling algorithms...

现在,警告。 Image#getScaledInstance既不是最快也不是最好的缩放算法......

Take a look at...

看一眼...

for more details...

更多细节...

回答by camickr

You can use the Stretch Icon. Just add the Icon to your component and scaling will happen automatically.

您可以使用拉伸图标。只需将图标添加到您的组件中,缩放就会自动发生。

回答by Younes Meridji

In this code an image is resized to have the same dimensions of the JButton's object that will contain it:

在此代码中,图像被调整为与包含它的 JButton 对象具有相同的尺寸:

JButton button = new JButton();
button.setBounds(x, y, width, height);
try{
    Image image = ImageIO.read(new File("icons/myImage.png")).getScaledInstance(width, height, Image.SCALE_DEFAULT);
    button.setIcon(new ImageIcon(image));
} 
catch (Exception e) {
}

回答by Hai Quan Le

You can try change the file extension(like "jpg, png, icon") to "gif". It worked for me in Eclipse

您可以尝试将文件扩展名(如"jpg, png, icon")更改为"gif"。它在 Eclipse 中对我有用