浏览图像文件并使用Java Swing显示它 [英] Browse for image file and display it using Java Swing

查看:94
本文介绍了浏览图像文件并使用Java Swing显示它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



为了参考,我上传了UI。



  

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;
文件targetFile;
BufferedImage targetImg;
public JPanel面板,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 ;

/ **
*启动应用程序。
* /
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(异常e){
e .printStackTrace();
}
}
});
}

/ **
*创建框架。
* /
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));

panel = new JPanel();
panel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0,0,0),1,true));
contentPane.add(panel,BorderLayout.WEST);

JButton btnBrowse =新的JButton(浏览);
btnBrowse.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
browseButtonActionPerformed(e);
}
});

JLabel lblSelectTargetPicture = new JLabel(选择目标图片..);

JButton btnDetect = new JButton(Detect);
btnDetect.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});

JButton btnAddDigit = new JButton(Add Digit);
btnAddDigit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});

JButton button = new JButton(Recognize);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});

panel_1 = new JPanel();
panel_1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0,0,0),1,true));

GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizo​​ntalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(6)
.addGroup(gl_panel。 createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addComponent(lblSelectTargetPicture)
.addGap(6)
.addComponent(btnBrowse))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(btnDetect)
.addGap(18)
.addComponent(btnAddDigit)))
.addGroup(gl_panel.createSequentialGroup()
.addGap(50)
.addComponent(button))
.addGroup(g l_panel.createSequentialGroup()
.addContainerGap()
.addComponent(panel_1,GroupLayout.PREFERRED_SIZE,182,GroupLayout.PREFERRED_SIZE))
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(7)
.addComponent(lblSelectTargetPicture))
.addGroup(gl_panel.createSequentialGroup()
.addGap(3)
.addComponent(btnBrowse)))
.addGap(18)
.addComponent(panel_1,GroupLayout.PREFERRED_SIZE,199,GroupLayout.PREFERRED_SIZE)
.addGap(22)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(btnDetect)
.addComponent(btnAddDigit))
.addGap(18)
.addComponent(button)
.addContainerGap())
);

panel.setLayout(gl_panel);
}
public BufferedImage rescale(BufferedImage originalImage)
{
BufferedImage resizedImage = new BufferedImage(baseSize,baseSize,BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage,0,0,baseSize,baseSize,null);
g.dispose();
return resizedImage;
}
public void setTarget(File reference)
{
try {
targetFile = reference;
targetImg = rescale(ImageIO.read(reference));
} catch(IOException ex){
Logger.getLogger(MainAppFrame.class.getName())。log(Level.SEVERE,null,ex);
}

panel_1.setLayout(new BorderLayout(0,0));
panel_1.add(new JLabel(new ImageIcon(targetImg)));
setVisible(true);
}
private void browseButtonActionPerformed(java.awt.event.ActionEvent evt){
JFileChooser fc = new JFileChooser(basePath);
fc.setFileFilter(new JPEGImageFileFilter());
int res = fc.showOpenDialog(null);
//我们有一个图像!
try {
if(res == JFileChooser.APPROVE_OPTION){
文件文件= fc.getSelectedFile();
setTarget(file);
} //糟糕!
else {
JOptionPane.showMessageDialog(null,
您必须选择一个图像作为参考。,Aborting ...,
JOptionPane.WARNING_MESSAGE);
}
} catch(异常iOException){
}

}
}




//JPEGImageFileFilter.java

包装GUI;

import java.io.File;

import javax.swing.filechooser.FileFilter;

/ *
*此类实现了通用文件名过滤器,允许列出/选择JPEG文件的
*。
* /
public class JPEGImageFileFilter extends FileFilter实现java.io.FileFilter
{
public boolean accept(File f)
{
if(f。 getName()。toLowerCase()。endsWith(。jpeg))return true;
if(f.getName()。toLowerCase()。endsWith(。jpg))return true;
if(f.isDirectory())返回true;
返回false;
}
public String getDescription()
{
返回JPEG文件;
}

}


解决方案

每次选择新图像时,您都会不必要地创建组件,并且出现错误:

  public void setTarget(文件参考){
// ....
panel_1.setLayout(new BorderLayout(0,0));
panel_1.add(new JLabel(new ImageIcon(targetImg)));
setVisible(true);

相反,我建议您将所有这些组件从get-go创建,在任何文件/图像已被选中,然后在此方法中,从Image创建一个ImageIcon,然后使用此图标设置已存在的JLabel图标而不是新的JLabel。这通过调用 myLabel.setIcon(new ImageIcon(targetImg));


My problem here is, after clicking Browse button it displays all files in a directory to choose, then the chosen image is displayed in GUI correctly. But When i click Browse button for the second time, it shows the old image only instead of showing the new one. Please help me in this.

For reference, i uploaded the UI.

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

        panel = new JPanel();
        panel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        contentPane.add(panel, BorderLayout.WEST);

        JButton btnBrowse = new JButton("Browse");
        btnBrowse.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browseButtonActionPerformed(e);
            }
        });

        JLabel lblSelectTargetPicture = new JLabel("Select target picture..");

        JButton btnDetect = new JButton("Detect");
        btnDetect.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });

        JButton btnAddDigit = new JButton("Add Digit");
        btnAddDigit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });

        JButton button = new JButton("Recognize");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });

        panel_1 = new JPanel();
        panel_1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));

        GroupLayout gl_panel = new GroupLayout(panel);
        gl_panel.setHorizontalGroup(
            gl_panel.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel.createSequentialGroup()
                    .addGap(6)
                    .addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_panel.createSequentialGroup()
                            .addComponent(lblSelectTargetPicture)
                            .addGap(6)
                            .addComponent(btnBrowse))
                        .addGroup(gl_panel.createSequentialGroup()
                            .addGap(10)
                            .addComponent(btnDetect)
                            .addGap(18)
                            .addComponent(btnAddDigit))))
                .addGroup(gl_panel.createSequentialGroup()
                    .addGap(50)
                    .addComponent(button))
                .addGroup(gl_panel.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 182, GroupLayout.PREFERRED_SIZE))
        );
        gl_panel.setVerticalGroup(
            gl_panel.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel.createSequentialGroup()
                    .addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_panel.createSequentialGroup()
                            .addGap(7)
                            .addComponent(lblSelectTargetPicture))
                        .addGroup(gl_panel.createSequentialGroup()
                            .addGap(3)
                            .addComponent(btnBrowse)))
                    .addGap(18)
                    .addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 199, GroupLayout.PREFERRED_SIZE)
                    .addGap(22)
                    .addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
                        .addComponent(btnDetect)
                        .addComponent(btnAddDigit))
                    .addGap(18)
                    .addComponent(button)
                    .addContainerGap())
        );

        panel.setLayout(gl_panel);
    }
    public BufferedImage rescale(BufferedImage originalImage)
    {
        BufferedImage resizedImage = new BufferedImage(baseSize, baseSize, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, baseSize, baseSize, null);
        g.dispose();
        return resizedImage;
    }
    public void setTarget(File reference)
    {
        try {
            targetFile = reference;
            targetImg = rescale(ImageIO.read(reference));
        } catch (IOException ex) {
            Logger.getLogger(MainAppFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        panel_1.setLayout(new BorderLayout(0, 0));
        panel_1.add(new JLabel(new ImageIcon(targetImg))); 
        setVisible(true);
    }
    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {
        JFileChooser fc = new JFileChooser(basePath);
        fc.setFileFilter(new JPEGImageFileFilter());
        int res = fc.showOpenDialog(null);
        // We have an image!
        try {
            if (res == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                setTarget(file);
            } // Oops!
            else {
                JOptionPane.showMessageDialog(null,
                        "You must select one image to be the reference.", "Aborting...",
                        JOptionPane.WARNING_MESSAGE);
            }
        } catch (Exception iOException) {
        }

    }
}




//JPEGImageFileFilter.java

package GUI;

import java.io.File;

import javax.swing.filechooser.FileFilter;

/*
* This class implements a generic file name filter that allows the listing/selection
* of JPEG files.
*/
public class JPEGImageFileFilter extends FileFilter implements java.io.FileFilter
 {
 public boolean accept(File f)
   {
   if (f.getName().toLowerCase().endsWith(".jpeg")) return true;
   if (f.getName().toLowerCase().endsWith(".jpg")) return true;
   if(f.isDirectory())return true;
   return false;
  }
 public String getDescription()
   {
   return "JPEG files";
   }

} 

解决方案

Each time a new image is selected, you're creating components unnecessarily and in error here:

public void setTarget(File reference) {
    //....
    panel_1.setLayout(new BorderLayout(0, 0));
    panel_1.add(new JLabel(new ImageIcon(targetImg))); 
    setVisible(true);

Instead I would recommend that you have all these components created from the get-go, before any file/image has been selected, and then in this method, create an ImageIcon from the Image, and then simply use this Icon to set the Icon of an already existng JLabel rather than a new JLabel. This is done simply by calling myLabel.setIcon(new ImageIcon(targetImg));

这篇关于浏览图像文件并使用Java Swing显示它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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