-1

I know this has been asked a ton of times, but I've searched everywhere and still haven't found an answer. I'm relatively new to Java. I have

JButton b[][];

Later, I assign b[3][3].setIcon(path). However, the image at path is always a small section of the actual image the size of the JButton. What I want is to re-size the image to fit the size of the JButton. Is there any way to do this? By the way, here's some code that's (I think) is important:

int n = 8;
int m = 8;

...

           b = new JButton[n][m];
           setLayout(new GridLayout(n,m));
           for (int y = 0;y<m;y++){
                   for (int x = 0;x<n;x++){
                           b[x][y] = new JButton(" ");
                           b[x][y].addActionListener(this);
                           add(b[x][y]);
                           b[x][y].setEnabled(true);
                   }
           }
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
kzhao14
  • 2,470
  • 14
  • 21
  • That's a really complex subject, you could start having 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/21070703/how-to-properly-refresh-image-in-jframe/21070799#21070799) and [this](http://stackoverflow.com/questions/14548808/scale-the-imageicon-automatically-to-label-size/14553003#14553003) for some ideas – MadProgrammer Jan 23 '16 at 21:58
  • OK, I'll check that out. – kzhao14 Jan 23 '16 at 22:04

2 Answers2

1

What you obviously need is a Icon Resizer method, something in the way of what I have provided below:

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

You can call this method after the image has already been applied to the JButton and after it has been added to whatever panel:

b[3][3].setIcon(path)
b[3][3].setIcon(resizeIcon((ImageIcon) b[3][3].getIcon(), 
    b[3][3].getWidth() - 15, b[3][3].getHeight() - 15)); 

or you could do it this way:

ImageIcon img =  new ImageIcon("MyImage.png");
Icon icn = resizeIcon(img, b[3][3].getWidth() - 15, b[3][3].getHeight() - 15);
b[3][3].setIcon(icn);
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22
1

What I want is to re-size the image to fit the size of the JButton.

You can use the Stretch Icon class.

It will allow you to automatically resize the Icon:

  1. to fill the space of the button, or
  2. keep the Icon proportion and fill the space of the button

The resizing is done dynamically so you don't need scaled images.

camickr
  • 321,443
  • 19
  • 166
  • 288