我有一個擴展JLabel的類,在標籤的整個innerArea上顯示圖像。
要做到這一點,我重寫的paintComponent這樣的:強制顯示JLabel子類
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(image != null) {
SwingUtilities.calculateInnerArea(this, innerArea);
g.drawImage(image, 0, 0, innerArea.width, innerArea.height, this);
}
}
我認爲它應該工作使用構造如下:
public ImageLabel(String img) {
super();
this.image = new ImageIcon(this.getClass().getResource(img)).getImage();
repaint();
}
但我有問題,該標籤已經基本沒有大小,因爲它沒有實際的內容。
當使用super(" ");
而不是一切看起來我實際上預期。
現在我想知道 - 這是一個合法的方式來解決這個問題,或者我錯過了一些其他(可能更好)的方式?
你爲什麼不乾脆調用'new JLabel(new ImageIcon(this.getClass()。getResource(img))。getImage())'? – BackSlash
據我發現,這樣ImageIcon將不會調整大小 –