繁体   English   中英

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

[英]Adding Icon to JButton without changing its size

我试图将Icon添加到JButton时,我的布局管理器(我使用GridBagLayout )会调整按钮的大小,并使其按图标的大小变大。

有办法避免这种情况吗?

您可以尝试JButton#setPreferedSize(...)

或者,您可以重写paintComponent方法:

JButton testButton = new JButton() {
   @Override
   protected void paintComponent(Graphics g) {
       super.paintComponent(g);
       g.drawImage(image, 0, 0, null);
   }
};

如果您想使用多个按钮来执行此操作,则最好为其创建一个类,例如:

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                          
    }                                           
}

我有同样的问题。 做这些事情:

  1. 使用图像处理程序调整图像大小以适合按钮。
  2. 使用setMininumSize()并设置所需的最小大小。

这可能会解决您的问题。

暂无
暂无

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

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