Java 在 JPanel 上显示 jpg 图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1242581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 07:21:44  来源:igfitidea点击:

Display a jpg image on a JPanel

javaimagejpanel

提问by burntsugar

What would be the most appropriate image type to display a jpg image (loaded from a local folder) on a JPanel?

在 JPanel 上显示 jpg 图像(从本地文件夹加载)最合适的图像类型是什么?

Cheers.

干杯。

采纳答案by Eugene Ryzhikov

ImageIcon image = new ImageIcon("image/pic1.jpg");
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add( label, BorderLayout.CENTER );

回答by Sean A.O. Harney

You could use a javax.swing.ImageIcon and add it to a JLabel using setIcon() method, then add the JLabel to the JPanel.

您可以使用 javax.swing.ImageIcon 并使用 setIcon() 方法将其添加到 JLabel,然后将 JLabel 添加到 JPanel。

回答by Tom

I'd probably use an ImageIcon and set it on a JLabel which I'd add to the JPanel.

我可能会使用 ImageIcon 并将其设置在我将添加到 JPanel 的 JLabel 上。

Here'sSun's docs on the subject matter.

这是Sun 关于该主题的文档。

回答by Per Alexandersson

I would use a Canvas that I add to the JPanel, and draw the image on the Canvas. But Canvas is a quite heavy object, sine it is from awt.

我会使用我添加到 JPanel 的画布,并在画布上绘制图像。但是 Canvas 是一个相当重的物体,因为它来自 awt。

回答by Handsken

You could also use

你也可以使用

ImageIcon background = new ImageIcon("Background/background.png");
JLabel label = new JLabel();
label.setBounds(0, 0, x, y);
label.setIcon(background);

JPanel panel = new JPanel();
panel.setLayout(null);
panel.add(label);

if your working with a absolut value as layout.

如果您使用绝对值作为布局。