浏览图像文件并使用Java Swing显示它

我的问题是,单击Browse按钮后,它会显示目录中的所有文件供选择,然后所选的图像会正确显示在GUI中。但是,当我第二次单击“浏览”按钮时,它仅显示旧图像,而不显示新图像。请帮助我。

package GUI;


import java.awt.BorderLayout;

import java.awt.EventQueue;

import java.awt.Graphics2D;


import javax.imageio.ImageIO;

import javax.swing.ImageIcon;

import javax.swing.JFileChooser;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.border.EmptyBorder;

import javax.swing.JLabel;

import javax.swing.JButton;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.swing.GroupLayout;

import javax.swing.GroupLayout.Alignment;



@SuppressWarnings("serial")

public class MainAppFrame extends JFrame {


    private JPanel contentPane;

    File targetFile;

    BufferedImage targetImg;

    public JPanel panel,panel_1;

    private static final int baseSize = 128;

    private static final String basePath =![enter image description here][1]

            "C:\\Documents and Settings\\Administrator\\Desktop\\Images";


    /**

     * Launch the application.

     */

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {

            public void run() {

                try {

                    MainAppFrame frame = new MainAppFrame();

                    frame.setVisible(true);

                    frame.setResizable(false);

                } catch (Exception e) {

                    e.printStackTrace();

                }

            }

        });

    }


    /**

     * Create the frame.

     */

    public MainAppFrame() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setBounds(100, 100, 550, 400);

        contentPane = new JPanel();

        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

        setContentPane(contentPane);

        contentPane.setLayout(new BorderLayout(0, 0));

幕布斯6054654
浏览 1129回答 3
3回答

不负相思意

每次选择新图像时,都在这里不必要地创建了组件,并且错误地出现在这里:public void setTarget(File reference) {    //....    panel_1.setLayout(new BorderLayout(0, 0));    panel_1.add(new JLabel(new ImageIcon(targetImg)));     setVisible(true);相反,我建议您在选择任何文件/图像之前,从一开始就创建所有这些组件,然后在此方法中,根据图像创建一个ImageIcon,然后简单地使用此Icon来设置已经存在的JLabel,而不是新的JLabel。只需调用myLabel.setIcon(new ImageIcon(targetImg));
打开App,查看更多内容
随时随地看视频慕课网APP