[英]Adding Icon to JButton without changing its size
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. 我试图将
Icon
添加到JButton
时,我的布局管理器(我使用GridBagLayout
)会调整按钮的大小,并使其按图标的大小变大。
Is there a way to avoid this? 有办法避免这种情况吗?
You could try JButton#setPreferedSize(...) 您可以尝试JButton#setPreferedSize(...)
Or you could override the paintComponent method: 或者,您可以重写paintComponent方法:
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. 这可能会解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.