Java 如何在 JPanel 中显示图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36395762/
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
How can I display an image in a JPanel
提问by FiroKun
My question here is how can I display an image into a JPanel? Other topics here asking something similar aren't clear to my about how can I do that.
我的问题是如何将图像显示到 JPanel 中?这里提出类似问题的其他主题对我来说不清楚我该怎么做。
I have a directory in my project folder that have image files Project Folder/GUI/img
, specifically gray.png
and green.png
which I want to display in a JPanel.
我在具有图像文件我的项目文件夹的目录Project Folder/GUI/img
,特别是gray.png
和green.png
我想在一个JPanel显示。
I tried with the following code using ImageIcon
and JLabel
that I found in other post:
我尝试使用以下代码ImageIcon
并JLabel
在其他帖子中找到:
ImageIcon image = new ImageIcon("GUI/img/gray.png");
JLabel label = new JLabel(image);
//JPanel panel is already initialized by the IDE
panel.add(label)
But doesn't work... The JPanel
remain empty without displaying any image. How can I do that?
但不起作用...JPanel
保持空白而不显示任何图像。我怎样才能做到这一点?
Additional to this, I want that the image inside the JPanel
change (gray.png
for green.png
) when some action is performed, for example pressing a button. I can archive that by the same method for display the image in the JPanel
right?
除此之外,我希望在执行某些操作(例如按下按钮)时JPanel
更改 ( gray.png
for green.png
)中的图像。我可以通过相同的方法将其存档以在JPanel
右侧显示图像吗?
Thanks in advance!
提前致谢!
EDIT: Here's an example of a test code for get this. The initialization is done automatically by the IDE.
编辑:这是获取此代码的测试代码示例。初始化由 IDE 自动完成。
import java.awt.Image;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class Sample extends javax.swing.JFrame {
public Sample() {
initComponents();
}
//Initialization
private void initComponents() {
PanelImage = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
javax.swing.GroupLayout PanelImageLayout = new javax.swing.GroupLayout(PanelImage);
PanelImage.setLayout(PanelImageLayout);
PanelImageLayout.setHorizontalGroup(
PanelImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
PanelImageLayout.setVerticalGroup(
PanelImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(61, 61, 61)
.addComponent(PanelImage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(239, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(PanelImage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(155, Short.MAX_VALUE))
);
pack();
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
try {
DisplayImage(PanelImage, "/GUI/img/gray.png");
} catch (Exception ex) {
Logger.getLogger(Sample.class.getName()).log(Level.SEVERE, null, ex);
}
}
//For display the url image in a JPanel
private void DisplayImage(JPanel jp, String url) throws IOException, Exception {
try {
Image image=ImageIO.read(this.getClass().getResource(url));
ImageIcon imageicon=new ImageIcon(image);
JLabel label=new JLabel(imageicon);
jp.add(label);
} catch (IOException ex) {
throw new IOException();
} catch (Exception ex) {
throw new Exception();
}
}
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Sample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Sample().setVisible(true);
}
});
}
// Variables declaration
private javax.swing.JPanel PanelImage;
}
The private void DisplayImage(JPanel jp, String url)
is what I need to work for display the image, from the url String url
in the JPanel jp
该private void DisplayImage(JPanel jp, String url)
是我需要为显示图像的工作,从URLString url
中JPanel jp
采纳答案by FiroKun
Looking for pieces of code in Google I ended up with a solution... And was applying the same pattern that previous comments refer. The code that gave me the solution was:
在谷歌中寻找代码片段我最终得到了一个解决方案......并且应用了与以前的评论相同的模式。给我解决方案的代码是:
label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/gray.png")))
label.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/gray.png")))
With that, I made then the method that I wanted to implement:
有了这个,我做了我想要实现的方法:
private static void DisplayImage(JPanel jp, String url) {
JLabel jl=new JLabel();
jl.setIcon(new javax.swing.ImageIcon(getClass().getResource(url)));
jp.add(jl);
}
Maybe this is not the perfect and most-correct solution, but works perfect to my, that is what I want.
也许这不是完美和最正确的解决方案,但对我来说很完美,这就是我想要的。
Thanks all for the answers and suggestions!
谢谢大家的回答和建议!
回答by scoots
I had a similar issue when I was working on creating Minesweeper. I ended up finding a solution and getting it to work by first loading an Image and then creating an ImageIcon from that Image.
我在创建扫雷时遇到了类似的问题。我最终找到了一个解决方案并通过首先加载图像然后从该图像创建一个 ImageIcon 来使其工作。
Image myImage = ImageIO.read(getClass().getResource("image_path.jpg"));
myImage = myImage.getScaledInstance(30, 30, java.awt.Image.SCALE_SMOOTH);
ImageIcon myImageIcon = new ImageIcon(myImage);
回答by shimbu shambu
you have to use ImageIcon(this.getClass().getResource("/Gui/img/gray.png"));
你必须使用 ImageIcon(this.getClass().getResource("/Gui/img/gray.png"));
here is example its working.
这是它的工作示例。
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ExImage extends JPanel
{
public ExImage()
{
ImageIcon imageIcon = new ImageIcon(this.getClass().getResource("/gray.png"));
JLabel label = new JLabel(imageIcon);
add(label);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.add(new ExImage());
frame.setVisible(true);
frame.setPreferredSize(new Dimension(200, 300));
}
}