Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JButton with auto resizing icon

843805Sep 22 2005 — edited Sep 22 2005
Hi,
I want to extend the JButon in order to make it auto resize the icon image to the button size itself.
I tried somethink like the following code and it work but there is some recursive side effect I cannot understand becouse I get a 100% CPU usage and from the print() I see the paint() method is called continuosly.


import java.awt.Graphics;
import java.awt.Image;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;

public class IconButton extends JButton {
private static final long serialVersionUID = 4049919355141829686L;
int cntr;
public IconButton(ImageIcon icon) {
super(icon);
}

public void paintComponent(Graphics g) {
System.out.println(cntr++);
Icon icn = getIcon();
if (icn instanceof ImageIcon) {
ImageIcon ii = (ImageIcon)icn;
Image img = ii.getImage();
img = img.getScaledInstance(getWidth(), getHeight(), Image.SCALE_AREA_AVERAGING);
icn = new ImageIcon(img);
super.setIcon(icn);
}
super.paintComponent(g);
}
}

Maybe there's a better way... for example by changing the icon only when the button size change: but how?

Thank in advance,

Carlo.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 20 2005
Added on Sep 22 2005
2 comments
842 views