I am trying to add an Icon
to the JButton
When I try to do this my Layout Manager (I use GridBagLayout
) resizes the button and makes it larger by the size of the icon.
Is there a way to avoid this?
You could try JButton#setPreferedSize(...)
Or you could override the paintComponent method:
JButton testButton = new JButton() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
};
If you want to do this with multiple buttons, it would be better to make a class for it ofcourse, something like:
class ImageButton extends JButton {
private final Image image;
public ImageButton(Image image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//drawing logic here
}
}
I had the same problem. Do these things:
This will probably fix your problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.