首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java Swing JLabel 圖標使用全解析:自定義繪製與 ImageIcon 圖片加載

     編輯:Java 綜合教學

JLabel 圖標基礎

JLabel 可同時顯示文本與圖標,通過實現 Icon 接口實現自定義繪製,或使用 ImageIcon 加載圖片資源。核心構造方法:

JLabel(String text, Icon icon, int horizontalAlignment)
JLabel(Icon icon)
JLabel(String text, int horizontalAlignment)

方式一:實現 Icon 接口自定義繪製

需實現三個方法:paintIcon()、getIconWidth()、getIconHeight()。

public class CircleIcon implements Icon {
    private final int diameter;
    private final Color color;
    
    public CircleIcon(int diameter, Color color) {
        this.diameter = diameter;
        this.color = color;
    }
    
    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(color);
        g2.fillOval(x, y, diameter, diameter);
        g2.dispose();
    }
    
    @Override public int getIconWidth() { return diameter; }
    @Override public int getIconHeight() { return diameter; }
}

// 使用示例
JLabel label = new JLabel("圓形圖標", new CircleIcon(32, Color.RED), SwingConstants.CENTER);
label.setVerticalTextPosition(SwingConstants.BOTTOM); // 文本在圖標下方
label.setHorizontalTextPosition(SwingConstants.CENTER);

方式二:ImageIcon 加載圖片資源

常用構造方法

  • ImageIcon(String filename) — 相對/絕對路徑
  • ImageIcon(URL location) — 推薦:類路徑加載
  • ImageIcon(byte[] imageData) — 字節數組
  • ImageIcon(Image image) — Image 對象

類路徑加載最佳實踐

// 獲取類路徑下圖片 URL
URL imgUrl = getClass().getResource("/images/logo.png"); // 絕對路徑(從 classpath 根)
// 或
URL imgUrl = MyClass.class.getResource("icon.png"); // 相對路徑(同包目錄)

if (imgUrl != null) {
    Icon icon = new ImageIcon(imgUrl);
    JLabel label = new JLabel("帶圖標標簽", icon, SwingConstants.LEFT);
    label.setIconTextGap(8); // 圖文間距
} else {
    System.err.println("圖片資源未找到");
}

完整可運行示例

public class ImageIconDemo extends JFrame {
    public ImageIconDemo() {
        setTitle("ImageIcon 示例");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        
        // 從類路徑加載
        URL url = getClass().getResource("/images/button.jpg");
        Icon icon = (url != null) ? new ImageIcon(url) : null;
        
        JLabel label = new JLabel("圖片標簽", icon, SwingConstants.CENTER);
        label.setHorizontalTextPosition(SwingConstants.CENTER);
        label.setVerticalTextPosition(SwingConstants.BOTTOM);
        label.setOpaque(true);
        label.setBackground(Color.LIGHT_GRAY);
        label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        add(label);
        pack();
        setLocationRelativeTo(null);
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new ImageIconDemo().setVisible(true));
    }
}

進階技巧與注意事項

掌握 Icon 自定義繪製與 ImageIcon 資源加載兩種方式,可滿足從簡單裝飾到複雜圖形化界面的各種需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
主題說明
圖標縮放 new ImageIcon(originalImage.getScaledInstance(w, h, Image.SMOOTH))
動態切換 label.setIcon(newIcon) 運行時動態更換
圖文位置 setHorizontalTextPosition、setVerticalTextPosition 控制文本相對圖標位置
透明度label.setOpaque(false) 保持背景透明
資源釋放 ImageIcon 內部持有 Image 引用,長期使用大量圖片需注意內存,可考慮 Image.flush()
高 DPI Retina/高分屏下建議提供 2x/3x 圖片或使用 SVG(需第三方庫如 Batik)