您如何将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);
答案 0 :(得分:1)
只需在项目中添加一个小方法,就可以这样做:
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);
如果您只想要图像而没有边框,只需将偏移量变量设置为0或完全去掉偏移量变量。