0

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);
Arnau
  • 19
  • 1
  • 1
  • 4
  • if you want to resize your image icon to 700px by 700px search about how the resize image – Blip Apr 30 '16 at 16:38
  • You might also like to have a look at [this](http://stackoverflow.com/questions/11959758/java-maintaining-aspect-ratio-of-jpanel-background-image/11959928#11959928) and [this](http://stackoverflow.com/questions/14115950/quality-of-image-after-resize-very-low-java/14116752#14116752) – MadProgrammer Apr 30 '16 at 21:40

1 Answers1

3

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

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

DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22