0

I'm trying to resize a JButton. I'm also trying to resize the image icon when the button is resized. I've used the ComponentListener. Here is the snippet of code trying to resize the image icon when the button size is increased:

jButton1.addComponentListener(new ComponentListener() {

    @Override
    public void componentShown(ComponentEvent e) {
        // ignore
    }

    @Override
    public void componentResized(ComponentEvent e) {
        Image newImg = img.getScaledInstance( jButton1.getWidth(), jButton1.getWidth(),  java.awt.Image.SCALE_SMOOTH ) ;
        ImageIcon icon = new ImageIcon(newImg);
        jButton1.setIcon(icon);
    }

    @Override
    public void componentMoved(ComponentEvent e) {
        // ignore
    }

    @Override
    public void componentHidden(ComponentEvent e) {
        // ignore
    }
});

But the problem is that only icon size is increased. Though the width is taken from the button itself. The button size stays fixed. If I do not change the icon, button size is increased accordingly.

Can anybody tell me what I'm missing here?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Red Devil
  • 349
  • 4
  • 16
  • 2
    You may need to `revalidate` the parent. Try using something like `jButton1.getParent().revalidate()` for example. This will also depend on the layout manager you are using. – MadProgrammer Jan 05 '14 at 23:07
  • It seems that issue is around revalidate. setIcon seems to call revalidate. If I call revalidate then my jButton does not get resized even without icon. – Red Devil Jan 05 '14 at 23:21
  • I've changed the layout to null layout from grid layout. It seems to have solved the issue. Thanks. – Red Devil Jan 06 '14 at 00:02
  • 1
    To be honest, that's not a particular good solution, something like GridBagLayout might be a better solution... – MadProgrammer Jan 06 '14 at 00:48
  • *"I've changed the layout to null layout.."* I'll go further than @MadProgrammer to point out that is an *horrid* solution that will cause more problems than it creates. 1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) One way to get image(s) for an example is to hot-link to the images seen in [this answer](http://stackoverflow.com/a/19209651/418556). – Andrew Thompson Jan 06 '14 at 03:08
  • The test code can be found there [link](http://pastebin.com/Q5dMKzSQ) – Red Devil Jan 06 '14 at 12:06

0 Answers0