WHAT'S NEW?

Loading an image in label using JFileChooser





ImageUpload.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
class ImageUpload extends JFrame implements ActionListener
{
BufferedImage img;
JButton jbtnImage;
JButton jbtn;
JFileChooser chooser;
ImageUpload()
{
super("Image");
setSize(900,700);
setResizable(true);
setDefaultCloseOperation(3);
Container c=getContentPane();
c.setBackground(Color.WHITE);
setLayout(null);

jbtnImage=new JButton("Image will be loaded here");
jbtnImage.setBounds(200,50,500,300);
jbtnImage.setBackground(Color.WHITE);
c.add(jbtnImage);
jbtn=new JButton("Load Image");
jbtn.setBounds(200,400,500,35);
jbtn.setBackground(new Color(158,202,78));
jbtn.setForeground(Color.WHITE);
jbtn.addActionListener(this);
c.add(jbtn);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource().equals(jbtn))
{
chooser= new JFileChooser();
chooser.setDialogTitle("Choose Your File");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    //below codes for select  the file
    int returnval=chooser.showOpenDialog(this);
    if(returnval==JFileChooser.APPROVE_OPTION)
    {
        File file = chooser.getSelectedFile();
        try
        {   //display the image in jlabel
            img=ImageIO.read(file);
jbtnImage.setText("");
           jbtnImage.setIcon(new ImageIcon(img));
        }
        catch(IOException e)
        {
        }
}
}
}
public static void main(String[] args)
{
new ImageUpload();
}
}

0 comments:

Post a Comment