java - 更新 JLabel 中包含的图像 - 问题

标签 java image swing jlabel

我目前无法开始工作的应用程序部分是能够滚动浏览并显示图像列表,一次一个。我从用户那里得到一个目录,假脱机浏览该目录中的所有文件,然后加载一个仅包含 jpeg 和 png 的数组。接下来,我想用第一张图片更新 JLabel,并提供上一张和下一张按钮依次滚动和显示每张图片。当我尝试显示第二张图片时,它没有得到更新......这是我目前所得到的:

public class CreateGallery
{
    private JLabel swingImage;

我用来更新图像的方法:

protected void updateImage(String name) 
{
    BufferedImage image = null;
    Image scaledImage = null;
    JLabel tempImage;

    try
    {
        image = ImageIO.read(new File(name));
    } catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // getScaledImage returns an Image that's been resized proportionally to my thumbnail constraints
    scaledImage = getScaledImage(image, THUMB_SIZE_X, THUMB_SIZE_Y);
    tempImage = new JLabel(new ImageIcon(scaledImage));
    swingImage = tempImage;
}

然后在我的 createAndShowGUI 方法中将 swingImage 放在......

private void createAndShowGUI() 
{
    //Create and set up the window.
    final JFrame frame = new JFrame();

    // Miscellaneous code in here - removed for brevity

    //  Create the Image Thumbnail swingImage and start up with a default image
    swingImage = new JLabel();
    String rootPath = new java.io.File("").getAbsolutePath();
    updateImage(rootPath + "/images/default.jpg");

    // Miscellaneous code in here - removed for brevity

    rightPane.add(swingImage, BorderLayout.PAGE_START);
    frame.add(rightPane, BorderLayout.LINE_END);
public static void main(String[] args) 
{
    SwingUtilities.invokeLater(new Runnable() 
    {
        public void run() 
        {
            UIManager.put("swing.boldMetal", Boolean.FALSE);
            new CreateGalleryXML().createAndShowGUI();
        }
    });
}

如果您已经了解了这里,第一张图像是我的 default.jpg,一旦我获得目录并识别该目录中的第一张图像,这就是我尝试更新 swingImage 时失败的地方。现在,我尝试使用 swingImage.setVisible() 和 swingImage.revalidate() 来强制它重新加载。我猜这是根本原因是我的 tempImage = new JLabel。但我不确定如何将 BufferedImage 或 Image 转换为 JLabel 以便仅更新 swingImage。

最佳答案

而不是创建 New InstanceJLabel对于每个 Image , 只需使用 JLabel#setIcon(...) JLabel 的方法更改图像。

一个小示例程序:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SlideShow extends JPanel
{
    private int i = 0;
    private Timer timer;
    private JLabel images = new JLabel();
    private Icon[] icons = {UIManager.getIcon("OptionPane.informationIcon"),
                            UIManager.getIcon("OptionPane.errorIcon"),
                            UIManager.getIcon("OptionPane.warningIcon")};
    private ImageIcon pictures1, pictures2, pictures3, pictures4;
    private ActionListener action = new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {                       
            i++;
            System.out.println(i);

            if(i == 1)
            {
                pictures1 = new ImageIcon("image/caIcon.png");
                images.setIcon(icons[i - 1]);
                System.out.println("picture 1 should be displayed here");
            }
            if(i == 2)
            {
                pictures2 = new ImageIcon("image/Keyboard.png");
                images.setIcon(icons[i - 1]);   
                System.out.println("picture 2 should be displayed here");
            }
            if(i == 3)
            {
                pictures3 = new ImageIcon("image/ukIcon.png");
                images.setIcon(icons[i - 1]);
                System.out.println("picture 3 should be displayed here");  
            }
            if(i == 4)
            {
                pictures4 = new ImageIcon("image/Mouse.png");
                images.setIcon(icons[0]);   
                System.out.println("picture 4 should be displayed here");  
            }
            if(i == 5)
            {
                timer.stop();
                System.exit(0);
            }
            revalidate();
            repaint();
        }
    };

    public SlideShow()
    {
        JFrame frame = new JFrame("SLIDE SHOW");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);

        frame.getContentPane().add(this);

        add(images);

        frame.setSize(300, 300);
        frame.setVisible(true); 
        timer = new Timer(2000, action);    
        timer.start();  
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new SlideShow();
            }
        });
    }
}

由于您是使用 ImageIO 完成的,这里有一个与此相关的很好的示例 JLabel using ImageIO

与您的案件相关的信息,以及正在发生的事情:

在你的 createAndShowGUI() 里面初始化 JLabel 的方法(swingImage),并将其添加到您的 JPanel凭借它间接到JFrame .

但现在在你的 updateImage() 里面方法,您正在初始化一个新的 JLabel ,现在它位于另一个内存位置,写为 tempImage = new JLabel(new ImageIcon(scaledImage));然后你指向你的swingImage(JLabel)指向这个新创建的 JLabel , 但这个新创建的 JLabel从未添加到 JPanel , 在任何时候。因此它不会是可见的,即使你尝试 revalidate()/repaint()/setVisible(...) .因此,要么您更改 updateImage(...) 的代码方法:

protected void updateImage(String name) 
{
    BufferedImage image = null;
    Image scaledImage = null;
    JLabel tempImage;

    try
    {
        image = ImageIO.read(new File(name));
    } 
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // getScaledImage returns an Image that's been resized 
    // proportionally to my thumbnail constraints
    scaledImage = getScaledImage(image, THUMB_SIZE_X, THUMB_SIZE_Y);
    tempImage = new JLabel(new ImageIcon(scaledImage));
    rightPane.remove(swingImage);
    swingImage = tempImage;
    rightPane.add(swingImage, BorderLayout.PAGE_START);
    rightPane.revalidate();
    rightPane.repaint(); // required sometimes
}

否则使用 JLabel.setIcon(...)如前所述:-)

更新了答案

这里看看 New JLabel放在老的位置,

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SlideShow extends JPanel
{
    private int i = 0;
    private Timer timer;
    private JLabel images = new JLabel();
    private Icon[] icons = {UIManager.getIcon("OptionPane.informationIcon"),
                            UIManager.getIcon("OptionPane.errorIcon"),
                            UIManager.getIcon("OptionPane.warningIcon")};
    private ActionListener action = new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {                       
            i++;
            System.out.println(i);          

            if(i == 4)
            {
                timer.stop();
                System.exit(0);
            }
            remove(images);
            JLabel temp = new JLabel(icons[i - 1]);
            images = temp;
            add(images);
            revalidate();
            repaint();
        }
    };

    private void createAndDisplayGUI()
    {
        JFrame frame = new JFrame("SLIDE SHOW");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);    

        this.setLayout(new FlowLayout(FlowLayout.LEFT));    

        add(images);

        frame.getContentPane().add(this, BorderLayout.CENTER);

        frame.setSize(300, 300);
        frame.setVisible(true); 
        timer = new Timer(2000, action);    
        timer.start();  
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new SlideShow().createAndDisplayGUI();
            }
        });
    }
}

对于您的问题:在我尝试过的两个选项中,一个比另一个更好吗?

setIcon(...)在另一种方式上有优势,从某种意义上说,在添加/删除 JLabel 之后你不必为 revalidate()/repaint() 烦恼.此外,您无需记住 JLabel 的位置每次,你添加它。它保留在它的位置,您只需调用一个方法来更改图像,没有任何附加条件,工作就完成了,没有任何麻烦。

对于问题 2:我有点怀疑,关于什么是 Array of Records

关于java - 更新 JLabel 中包含的图像 - 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10051638/

相关文章:

java - 如何使用 DSL 为 ack/nack 和返回队列配置 amqp-outbound 适配器?

java - 使用okhttp3时空HTTP获取响应体

java - Android Studio - keystore 被篡改,或密码不正确

java - 具有多个 swing UI 的 EventQueue.invokeLater

java - 有没有办法自定义JLabel?

java - 根据映射到类的 yaml 中的条件查找 "row"字段

css - 在 CSS 中添加模糊边框

image - 如何确定图像的编码

php - 图片上传后无法显示

java - JTextField 中的文本未完全显示