原文:http://zetcode.com/java/imageicon/

在本教程中,我们将使用ImageIcon。 我们将绘制一个图标,缩放一个图标,创建一个自定义图标,并将图标放入各种 Swing 组件中。

ImageIcon

Icon是固定大小的小图片,通常用于装饰组件。 ImageIconIcon接口的实现,可从图像绘制图标。 可以从 URL,文件名或字节数组创建图像。

  1. paintIcon(Component c, Graphics g, int x, int y)

IconpaintIcon()方法在指定位置绘制图标。

ImageIcon构造器

ImageIcon具有多个构造器,包括:

  • ImageIcon(byte[] imageData) - 从字节数组创建ImageIcon
  • ImageIcon(Image image) — 从图像对象创建ImageIcon
  • ImageIcon(String filename) - 创建一个ImageIcon指定的文件。
  • ImageIcon(URL location) - 从指定的 URL 创建一个ImageIcon

ImageIcon可以处理 PNG,JPEG 和 GIF 图像。 如果要使用 BMP 或 ICO 图像,可以使用 image4j 库。

绘制图标

在第一个示例中,我们将在面板上绘制一个图标。

PaintingIconEx.java

  1. package com.zetcode;
  2. import java.awt.Container;
  3. import java.awt.Dimension;
  4. import java.awt.EventQueue;
  5. import java.awt.Graphics;
  6. import javax.swing.GroupLayout;
  7. import javax.swing.ImageIcon;
  8. import javax.swing.JComponent;
  9. import javax.swing.JFrame;
  10. import javax.swing.JPanel;
  11. class DrawingPanel extends JPanel {
  12. private ImageIcon icon;
  13. public DrawingPanel() {
  14. loadImage();
  15. initPanel();
  16. }
  17. private void loadImage() {
  18. icon = new ImageIcon("book.jpg");
  19. }
  20. private void initPanel() {
  21. int w = icon.getIconWidth();
  22. int h = icon.getIconHeight();
  23. setPreferredSize(new Dimension(w, h));
  24. }
  25. @Override
  26. public void paintComponent(Graphics g) {
  27. super.paintComponent(g);
  28. icon.paintIcon(this, g, 0, 0);
  29. }
  30. }
  31. public class PaintingIconEx extends JFrame {
  32. public PaintingIconEx() {
  33. initUI();
  34. }
  35. private void initUI() {
  36. DrawingPanel dpnl = new DrawingPanel();
  37. createLayout(dpnl);
  38. setTitle("Image");
  39. setLocationRelativeTo(null);
  40. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  41. }
  42. private void createLayout(JComponent... arg) {
  43. Container pane = getContentPane();
  44. GroupLayout gl = new GroupLayout(pane);
  45. pane.setLayout(gl);
  46. gl.setHorizontalGroup(gl.createSequentialGroup()
  47. .addComponent(arg[0])
  48. );
  49. gl.setVerticalGroup(gl.createParallelGroup()
  50. .addComponent(arg[0])
  51. );
  52. pack();
  53. }
  54. public static void main(String[] args) {
  55. EventQueue.invokeLater(() -> {
  56. JFrame ex = new PaintingIconEx();
  57. ex.setVisible(true);
  58. });
  59. }
  60. }

该示例将文件系统中的图像加载到ImageIcon中并将其绘制在JPanel组件上。

  1. private void loadImage() {
  2. icon = new ImageIcon("book.jpg");
  3. }

我们将 JPG 图像加载到ImageIcon中。 该图像位于项目根目录中。

  1. private void initPanel() {
  2. int w = icon.getIconWidth();
  3. int h = icon.getIconHeight();
  4. setPreferredSize(new Dimension(w, h));
  5. }

initPanel()方法中,我们使用getIconWidth()getIconHeight()方法确定图标的宽度和高度。 我们设置面板的首选大小以匹配图标大小。

  1. @Override
  2. public void paintComponent(Graphics g) {
  3. super.paintComponent(g);
  4. icon.paintIcon(this, g, 0, 0);
  5. }

paintComponent()方法中,我们使用paintIcon()方法在面板上绘制图标。

`ImageIcon`教程 - 图1

图:绘画图标

缩放图像

以下示例显示了缩放图像的简单方法。

ImageIconScaleEx.java

  1. package com.zetcode;
  2. import java.awt.Container;
  3. import java.awt.EventQueue;
  4. import java.awt.Image;
  5. import javax.swing.GroupLayout;
  6. import javax.swing.ImageIcon;
  7. import javax.swing.JComponent;
  8. import javax.swing.JFrame;
  9. import static javax.swing.JFrame.EXIT_ON_CLOSE;
  10. import javax.swing.JLabel;
  11. public class ImageIconScaleEx extends JFrame {
  12. public ImageIconScaleEx() {
  13. initUI();
  14. }
  15. private void initUI() {
  16. ImageIcon originalIcon = new ImageIcon("slovakia.png");
  17. JLabel originalLabel = new JLabel(originalIcon);
  18. int width = originalIcon.getIconWidth() / 2;
  19. int height = originalIcon.getIconHeight() / 2;
  20. Image scaled = scaleImage(originalIcon.getImage(), width, height);
  21. ImageIcon scaledIcon = new ImageIcon(scaled);
  22. JLabel newLabel = new JLabel(scaledIcon);
  23. createLayout(originalLabel, newLabel);
  24. setTitle("Scaled icon");
  25. setLocationRelativeTo(null);
  26. setDefaultCloseOperation(EXIT_ON_CLOSE);
  27. }
  28. private Image scaleImage(Image image, int w, int h) {
  29. Image scaled = image.getScaledInstance(w, h, Image.SCALE_SMOOTH);
  30. return scaled;
  31. }
  32. private void createLayout(JComponent... arg) {
  33. Container pane = getContentPane();
  34. GroupLayout gl = new GroupLayout(pane);
  35. pane.setLayout(gl);
  36. gl.setAutoCreateContainerGaps(true);
  37. gl.setAutoCreateGaps(true);
  38. gl.setHorizontalGroup(gl.createSequentialGroup()
  39. .addComponent(arg[0])
  40. .addComponent(arg[1])
  41. );
  42. gl.setVerticalGroup(gl.createParallelGroup()
  43. .addComponent(arg[0])
  44. .addComponent(arg[1])
  45. );
  46. pack();
  47. }
  48. public static void main(String[] args) {
  49. EventQueue.invokeLater(() -> {
  50. ImageIconScaleEx ex = new ImageIconScaleEx();
  51. ex.setVisible(true);
  52. });
  53. }
  54. }

窗口上显示了两个图像:原始图像及其旁边的缩放图像。

  1. ImageIcon originalIcon = new ImageIcon("slovakia.png");

我们将 PNG 图像读取到ImageIcon中。 该图像位于项目根目录中。

  1. int width = originalIcon.getIconWidth() / 2;
  2. int height = originalIcon.getIconHeight() / 2;

我们使用getIconWidth()getIconHeight()方法获得原始图像的宽度和高度。

  1. Image scaled = scaleImage(originalIcon.getImage(), width, height);

我们将图标的Image,其widthheight传递给scaleImage()方法,在其中执行缩放操作。

  1. private Image scaleImage(Image image, int w, int h) {
  2. Image scaled = image.getScaledInstance(w, h, Image.SCALE_SMOOTH);
  3. return scaled;
  4. }

getScaledInstance()创建Image的缩放版本。 我们使用Image.SCALE_SMOOTH缩放操作,该操作对图像平滑度的优先级高于缩放速度。

  1. ImageIcon scaledIcon = new ImageIcon(scaled);
  2. JLabel newLabel = new JLabel(scaledIcon);

我们从Image创建一个ImageIcon,并将其传递给JLabel组件。

`ImageIcon`教程 - 图2

图:缩放 image

自定义图标

Swing 绘画 API 也可以用于创建自定义图标。 图形上下文将传递给paintIcon()方法。

CustomIconEx.java

  1. package com.zetcode;
  2. import java.awt.BasicStroke;
  3. import java.awt.Color;
  4. import java.awt.Component;
  5. import java.awt.EventQueue;
  6. import java.awt.Graphics;
  7. import java.awt.Graphics2D;
  8. import javax.swing.Icon;
  9. import javax.swing.JFrame;
  10. import javax.swing.JLabel;
  11. class MissingIcon implements Icon {
  12. private final int WIDTH = 32;
  13. private final int HEIGHT = 32;
  14. private final BasicStroke stroke = new BasicStroke(5);
  15. @Override
  16. public void paintIcon(Component c, Graphics g, int x, int y) {
  17. doDrawing(g, x, y);
  18. }
  19. public void doDrawing(Graphics g, int x, int y) {
  20. Graphics2D g2d = (Graphics2D) g.create();
  21. g2d.setColor(Color.white);
  22. g2d.fillRect(x + 1, y + 1, WIDTH - 2, HEIGHT - 2);
  23. g2d.setColor(Color.darkGray);
  24. g2d.drawRect(x + 1, y + 1, WIDTH - 2, HEIGHT - 2);
  25. g2d.setColor(Color.red);
  26. g2d.setStroke(stroke);
  27. g2d.drawLine(x + 10, y + 10, x + WIDTH - 10, y + HEIGHT - 10);
  28. g2d.drawLine(x + 10, y + HEIGHT - 10, x + WIDTH - 10, y + 10);
  29. g2d.dispose();
  30. }
  31. @Override
  32. public int getIconWidth() {
  33. return WIDTH;
  34. }
  35. @Override
  36. public int getIconHeight() {
  37. return HEIGHT;
  38. }
  39. }
  40. class MyLabel extends JLabel {
  41. public MyLabel(Icon icon) {
  42. super(icon);
  43. }
  44. @Override
  45. public boolean isOpaque() {
  46. return true;
  47. }
  48. }
  49. public class CustomIconEx extends JFrame {
  50. public CustomIconEx() {
  51. initUI();
  52. }
  53. private void initUI() {
  54. JLabel lbl = new MyLabel(new MissingIcon());
  55. lbl.setBackground(Color.gray);
  56. add(lbl);
  57. setSize(250, 150);
  58. setTitle("Custom icon");
  59. setLocationRelativeTo(null);
  60. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  61. }
  62. public static void main(String[] args) {
  63. EventQueue.invokeLater(() -> {
  64. CustomIconEx ex = new CustomIconEx();
  65. ex.setVisible(true);
  66. });
  67. }
  68. }

该示例创建一个缺少的自定义图标,并在带有JLabel的窗口上显示该图标。

  1. class MissingIcon implements Icon {

要创建自定义图标,我们实现Icon接口。

  1. @Override
  2. public int getIconWidth() {
  3. return WIDTH;
  4. }
  5. @Override
  6. public int getIconHeight() {
  7. return HEIGHT;
  8. }

我们重写getIconWidth()getIconHeight()方法,它们确定图标的大小。

  1. @Override
  2. public void paintIcon(Component c, Graphics g, int x, int y) {
  3. doDrawing(g, x, y);
  4. }

我们覆盖了paintIcon()方法,在该方法中绘制了图标。 Graphics对象提供了许多绘制 2D 形状并获取有关应用图形环境的信息的方法。

  1. public void doDrawing(Graphics g, int x, int y) {
  2. Graphics2D g2d = (Graphics2D) g.create();
  3. g2d.setColor(Color.white);
  4. g2d.fillRect(x + 1, y + 1, WIDTH - 2, HEIGHT - 2);
  5. g2d.setColor(Color.darkGray);
  6. g2d.drawRect(x + 1, y + 1, WIDTH - 2, HEIGHT - 2);
  7. g2d.setColor(Color.red);
  8. g2d.setStroke(stroke);
  9. g2d.drawLine(x + 10, y + 10, x + WIDTH - 10, y + HEIGHT - 10);
  10. g2d.drawLine(x + 10, y + HEIGHT - 10, x + WIDTH - 10, y + 10);
  11. g2d.dispose();
  12. }

doDrawing()方法内部,我们绘制了图标。 该过程与paintComponent()方法中的绘制相同。 Graphics2D类扩展了Graphics类,以提供对几何,坐标转换,颜色管理和文本布局的更复杂的控制。

  1. class MyLabel extends JLabel {
  2. public MyLabel(Icon icon) {
  3. super(icon);
  4. }
  5. @Override
  6. public boolean isOpaque() {
  7. return true;
  8. }
  9. }

我们有一个自定义的MyLabel组件。 我们将其设为不透明,即标签具有背景。

  1. JLabel lbl = new MyLabel(new MissingIcon());

图标设置为标签组件。

`ImageIcon`教程 - 图3

图:缺少自定义图标

ImageIcon按钮

可以将ImageIcons放置在JButton组件上。

ImageIconButtonsEx.java

  1. package com.zetcode;
  2. import java.awt.Container;
  3. import java.awt.EventQueue;
  4. import javax.swing.GroupLayout;
  5. import javax.swing.ImageIcon;
  6. import javax.swing.JButton;
  7. import javax.swing.JComponent;
  8. import javax.swing.JFrame;
  9. import static javax.swing.JFrame.EXIT_ON_CLOSE;
  10. public class ImageIconButtonsEx extends JFrame {
  11. public ImageIconButtonsEx() {
  12. initUI();
  13. }
  14. private void initUI() {
  15. ImageIcon quitIcon = new ImageIcon("quit.png");
  16. ImageIcon saveIcon = new ImageIcon("save.png");
  17. ImageIcon homeIcon = new ImageIcon("home.png");
  18. JButton quitBtn = new JButton(quitIcon);
  19. JButton saveBtn = new JButton(saveIcon);
  20. JButton homeBtn = new JButton(homeIcon);
  21. createLayout(quitBtn, saveBtn, homeBtn);
  22. setTitle("JButtons");
  23. setLocationRelativeTo(null);
  24. setDefaultCloseOperation(EXIT_ON_CLOSE);
  25. }
  26. private void createLayout(JComponent... arg) {
  27. Container pane = getContentPane();
  28. GroupLayout gl = new GroupLayout(pane);
  29. pane.setLayout(gl);
  30. gl.setAutoCreateContainerGaps(true);
  31. gl.setAutoCreateGaps(true);
  32. gl.setHorizontalGroup(gl.createSequentialGroup()
  33. .addComponent(arg[0])
  34. .addComponent(arg[1])
  35. .addComponent(arg[2])
  36. );
  37. gl.setVerticalGroup(gl.createParallelGroup()
  38. .addComponent(arg[0])
  39. .addComponent(arg[1])
  40. .addComponent(arg[2])
  41. );
  42. gl.linkSize(arg[0], arg[1], arg[2]);
  43. pack();
  44. }
  45. public static void main(String[] args) {
  46. EventQueue.invokeLater(() -> {
  47. ImageIconButtonsEx ex = new ImageIconButtonsEx();
  48. ex.setVisible(true);
  49. });
  50. }
  51. }

我们有三个按钮。 它们每个都显示一个ImageIcon

  1. ImageIcon quitIcon = new ImageIcon("quit.png");
  2. ImageIcon saveIcon = new ImageIcon("save.png");
  3. ImageIcon homeIcon = new ImageIcon("home.png");

创建了三个ImageIcons。 我们将文件名传递给每个构造器。 PNG 文件位于项目根目录中。

  1. JButton quitBtn = new JButton(quitIcon);
  2. JButton saveBtn = new JButton(saveIcon);
  3. JButton homeBtn = new JButton(homeIcon);

JButton组件接受ImageIcon作为参数。

`ImageIcon`教程 - 图4

图:图像 buttons

JFrame图标

JFrame组件可以在其标题栏中显示一个图标。 它显示在标题栏的左侧。

FrameIconEx.java

  1. package com.zetcode;
  2. import java.awt.EventQueue;
  3. import javax.swing.ImageIcon;
  4. import javax.swing.JFrame;
  5. import static javax.swing.JFrame.EXIT_ON_CLOSE;
  6. public class FrameIconEx extends JFrame {
  7. public FrameIconEx() {
  8. initUI();
  9. }
  10. private void initUI() {
  11. ImageIcon webIcon = new ImageIcon("web.png");
  12. setIconImage(webIcon.getImage());
  13. setTitle("Icon");
  14. setSize(300, 200);
  15. setLocationRelativeTo(null);
  16. setDefaultCloseOperation(EXIT_ON_CLOSE);
  17. }
  18. public static void main(String[] args) {
  19. EventQueue.invokeLater(() -> {
  20. FrameIconEx ex = new FrameIconEx();
  21. ex.setVisible(true);
  22. });
  23. }
  24. }

web.png是一个很小的22x22px图像文件。

  1. ImageIcon webIcon = new ImageIcon("web.png");

我们从位于项目根目录中的 PNG 文件创建一个ImageIcon

  1. setIconImage(webIcon.getImage());

setIconImage()设置要显示为该窗口图标的图像。 getImage()返回图标的Image

`ImageIcon`教程 - 图5

图:图标

JLabel中的ImageIcon

在下面的示例中,我们将ImageIcons放入JLabel组件中。

ImageIconLabelEx.java

  1. package com.zetcode;
  2. import java.awt.Container;
  3. import java.awt.EventQueue;
  4. import javax.swing.GroupLayout;
  5. import javax.swing.ImageIcon;
  6. import javax.swing.JComponent;
  7. import javax.swing.JFrame;
  8. import static javax.swing.JFrame.EXIT_ON_CLOSE;
  9. import javax.swing.JLabel;
  10. public class ImageIconLabelEx extends JFrame {
  11. public ImageIconLabelEx() {
  12. initUI();
  13. }
  14. private void initUI() {
  15. JLabel lbl1 = new JLabel(new ImageIcon("cpu.png"));
  16. JLabel lbl2 = new JLabel(new ImageIcon("drive.png"));
  17. JLabel lbl3 = new JLabel(new ImageIcon("laptop.png"));
  18. JLabel lbl4 = new JLabel(new ImageIcon("player.png"));
  19. JLabel lbl5 = new JLabel(new ImageIcon("pda.png"));
  20. createLayout(lbl1, lbl2, lbl3, lbl4, lbl5);
  21. setTitle("Icons");
  22. setLocationRelativeTo(null);
  23. setDefaultCloseOperation(EXIT_ON_CLOSE);
  24. }
  25. private void createLayout(JComponent... arg) {
  26. Container pane = getContentPane();
  27. GroupLayout gl = new GroupLayout(pane);
  28. pane.setLayout(gl);
  29. gl.setAutoCreateContainerGaps(true);
  30. gl.setAutoCreateGaps(true);
  31. gl.setHorizontalGroup(gl.createSequentialGroup()
  32. .addComponent(arg[0])
  33. .addComponent(arg[1])
  34. .addComponent(arg[2])
  35. .addComponent(arg[3])
  36. .addComponent(arg[4])
  37. );
  38. gl.setVerticalGroup(gl.createParallelGroup()
  39. .addComponent(arg[0])
  40. .addComponent(arg[1])
  41. .addComponent(arg[2])
  42. .addComponent(arg[3])
  43. .addComponent(arg[4])
  44. );
  45. pack();
  46. }
  47. public static void main(String[] args) {
  48. EventQueue.invokeLater(() -> {
  49. ImageIconLabelEx ex = new ImageIconLabelEx();
  50. ex.setVisible(true);
  51. });
  52. }
  53. }

项目根目录中有五个 PNG 文件。 它们显示在JLabel组件的窗口中。

  1. JLabel lbl1 = new JLabel(new ImageIcon("cpu.png"));
  2. JLabel lbl2 = new JLabel(new ImageIcon("drive.png"));
  3. JLabel lbl3 = new JLabel(new ImageIcon("laptop.png"));
  4. JLabel lbl4 = new JLabel(new ImageIcon("player.png"));
  5. JLabel lbl5 = new JLabel(new ImageIcon("pda.png"));

JLabel具有一个构造器,该构造器将ImageIcon作为参数。

`ImageIcon`教程 - 图6

图:图标s in labels

JTabbedPane中的ImageIcon

JTabbedPane是 Swing 组件,允许用户通过单击选项卡在一组组件之间切换。 这些选项卡可以包含ImageIcons

ImageIconTabbedPaneEx

  1. package com.zetcode;
  2. import java.awt.Container;
  3. import java.awt.Dimension;
  4. import java.awt.EventQueue;
  5. import javax.swing.GroupLayout;
  6. import javax.swing.ImageIcon;
  7. import javax.swing.JComponent;
  8. import javax.swing.JFrame;
  9. import static javax.swing.JFrame.EXIT_ON_CLOSE;
  10. import javax.swing.JPanel;
  11. import javax.swing.JTabbedPane;
  12. public class ImageIconTabbedPaneEx extends JFrame {
  13. public ImageIconTabbedPaneEx() {
  14. initUI();
  15. }
  16. private void initUI() {
  17. ImageIcon icon1 = new ImageIcon("dot1.png");
  18. ImageIcon icon2 = new ImageIcon("dot2.png");
  19. ImageIcon icon3 = new ImageIcon("dot3.png");
  20. JTabbedPane tbp = new JTabbedPane();
  21. tbp.setPreferredSize(new Dimension(350, 250));
  22. tbp.addTab("", icon1, new JPanel());
  23. tbp.addTab("", icon2, new JPanel());
  24. tbp.addTab("", icon3, new JPanel());
  25. createLayout(tbp);
  26. setTitle("Icons");
  27. setLocationRelativeTo(null);
  28. setDefaultCloseOperation(EXIT_ON_CLOSE);
  29. }
  30. private void createLayout(JComponent... arg) {
  31. Container pane = getContentPane();
  32. GroupLayout gl = new GroupLayout(pane);
  33. pane.setLayout(gl);
  34. gl.setAutoCreateContainerGaps(true);
  35. gl.setAutoCreateGaps(true);
  36. gl.setHorizontalGroup(gl.createSequentialGroup()
  37. .addComponent(arg[0])
  38. );
  39. gl.setVerticalGroup(gl.createParallelGroup()
  40. .addComponent(arg[0])
  41. );
  42. pack();
  43. }
  44. public static void main(String[] args) {
  45. EventQueue.invokeLater(() -> {
  46. ImageIconTabbedPaneEx ex = new ImageIconTabbedPaneEx();
  47. ex.setVisible(true);
  48. });
  49. }
  50. }

该示例在JTabbedPane组件的选项卡中显示ImageIcons

  1. ImageIcon icon1 = new ImageIcon("dot1.png");

ImageIcon已创建。

  1. JTabbedPane tbp = new JTabbedPane();

JTabbedPane已创建。

  1. tbp.addTab("", icon1, new JPanel());

addTab()方法的第二个参数是ImageIcon

`ImageIcon`教程 - 图7

图:JTabbedPane图标

本教程专门针对 Java ImageIcon。 您可能也对相关教程感兴趣:用 Java 读写 ICO 图像Java Swing 教程Java 教程用 Java 显示图像