ImageIcon的大小适合JButton [英] Fit size of an ImageIcon to a JButton

查看:165
本文介绍了ImageIcon的大小适合JButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使ImageIcon的大小适合JButton?我想将ImageIcon的大小调整为Button的大小

Hi how can I fit the size of a ImageIcon to a JButton? I want to adjust the size of the ImageIcon to the size of the Button

JFrame frame2 = new JFrame("Tauler Joc");
JPanel panell = new JPanel();
ImageIcon icon = new ImageIcon("king.jpg");
JButton jb= new JButton(icon);
jb.setBounds(200,200,700,700);
panell.add(jb);
frame2.add(panell);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

推荐答案

您可以通过向项目中添加一些方法来实现此目的:

You can do it this way by simply adding a little method to your project:

private static Icon resizeIcon(ImageIcon icon, int resizedWidth, int resizedHeight) {
    Image img = icon.getImage();  
    Image resizedImage = img.getScaledInstance(resizedWidth, resizedHeight,  java.awt.Image.SCALE_SMOOTH);  
    return new ImageIcon(resizedImage);
}

现在,要在示例代码中使用此方法:

Now, to use this method in your example code:

JFrame frame2 = new JFrame("Tauler Joc");
JPanel panell = new JPanel();
ImageIcon icon = new ImageIcon("king.jpg");
JButton jb= new JButton();
jb.setBounds(200,200,700,700);
panell.add(jb);

// Set image to size of JButton...
int offset = jb.getInsets().left;
jb.setIcon(resizeIcon(icon, jb.getWidth() - offset, jb.getHeight() - offset));

frame2.add(panell);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

如果只需要图像且没有边框,则只需将offset变量设置为0或完全摆脱offset变量即可.

If you just want the image and no border just set the offset variable to 0 or get rid of the offset variable altogether.

这篇关于ImageIcon的大小适合JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆