嗨,我如何使ImageIcon的大小适合JButton?我想将ImageIcon的大小调整为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);
您可以通过在项目中添加一些方法来做到这一点:
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); }
现在,在示例代码中使用此方法:
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变量。