[英]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
}
}
我有同樣的問題。 做這些事情:
這可能會解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.