且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将图像添加到 JFrame

更新时间:2023-12-05 18:03:22

Swing 中没有提供专门的图像组件(我认为这很可悲).所以,有几个选择:

There is no specialized image component provided in Swing (which is sad in my opinion). So, there are a few options:

  1. 正如@Reimeus 所说:使用带有图标的 JLabel.
  2. 在窗口构建器中创建一个 JPanel,它将表示图像的位置.然后使用几行代码将您自己的自定义图像组件添加到 JPanel,您将永远不必更改.它们应该如下所示:

  1. As @Reimeus said: Use a JLabel with an icon.
  2. Create in the window builder a JPanel, that will represent the location of the image. Then add your own custom image component to the JPanel using a few lines of code you will never have to change. They should look like this:

JImageComponent ic = new JImageComponent(myImageGoesHere);
imagePanel.add(ic);

其中 JImageComponent 是一个自创类,它扩展了 JComponent,覆盖了 paintComponent() 方法来绘制图像.

where JImageComponent is a self created class that extends JComponent that overrides the paintComponent() method to draw the image.