簡體   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