如何在JPanel中显示图像 [英] How can I display an image in a JPanel

查看:157
本文介绍了如何在JPanel中显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是如何在JPanel中显示图像?我对如何做到这一点不清楚,这里的其他主题也提出了类似的要求.

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.

我的项目文件夹中有一个目录,其中包含图像文件Project Folder/GUI/img,尤其是gray.pnggreen.png,它们要显示在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.

我尝试使用在其他帖子中找到的ImageIconJLabel的以下代码:

I tried with the following code using ImageIcon and JLabel that I found in other post:

ImageIcon image = new ImageIcon("GUI/img/gray.png");
JLabel label = new JLabel(image);

//JPanel panel is already initialized by the IDE
panel.add(label)

但是不起作用... JPanel保持空白,不显示任何图像.我该怎么办?

But doesn't work... The JPanel remain empty without displaying any image. How can I do that?

此外,我希望在执行某些操作(例如按下按钮)时,更改JPanel中的图像(对于green.pnggray.png).我可以通过相同的方法将其存档,以在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?

提前谢谢!

这是获得此测试代码的示例.初始化由IDE自动完成.

Here's an example of a test code for get this. The initialization is done automatically by the 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;                
}

private void DisplayImage(JPanel jp, String url)是我需要工作的,用于显示图像,来自JPanel jp

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

推荐答案

我在Google中寻找代码段,最终得到了一个解决方案...并且所采用的模式与以前的注释所引用的模式相同. 给我解决方案的代码是:

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")))

然后,我制作了要实现的方法:

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!

这篇关于如何在JPanel中显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆