简体   繁体   English

将图标添加到JButton而不更改其大小

[英]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: 做这些事情:

  1. Resize your image to fit the button with an image manipulating program. 使用图像处理程序调整图像大小以适合按钮。
  2. use setMininumSize() and set the minimum size you want. 使用setMininumSize()并设置所需的最小大小。

This will probably fix your problem. 这可能会解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM