Monday, 20 April 2015

How To Upload Image In Java Program Using JFile Chooser

This tutorial shows how to create file chooser and open image using it.In many cases user have to import image in his application this tutorial shows how to import images in java program using file chooser.In this tutorial I have used little bit file handling.So if you don't have knowledge regarding this then see  file handling in java.
In this tutorial I have use setIcon methods its general constructor are shown below 

CONSTRUCTORS OF SETICON:


  • setIcon(Image)
  • setIcon(Image,String)
  • setIcon(URL)
  • setIcon(URL,String)
  • setIcon(String)
  • setIcon(String,String)
In this tutorial we have use first constructor you can use others depending upon conditions.Here image specify the image which has to be used as a icon,String specifies the textual description of a
image the URL specifies the destination of a image from which image has to be loaded

NOTE:The image should be in JPEG,PNG or in GIF format. 

HEADING:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class tab extends JFrame
implements ActionListener

 {
JButton jb;
JFileChooser open;
JLabel l1;
tab()
{
super();
setTitle("File chooser");
setSize(250, 300);
setVisible(true);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);  
jb =new JButton("Choose Image");
l1 =new JLabel();
FlowLayout f=new FlowLayout();
setLayout(f);
add(jb);
add(l1);
jb.addActionListener(this);
jb.setActionCommand("BUTTON 1");
}
public void actionPerformed(ActionEvent ae){
if ("BUTTON 1".equals(ae.getActionCommand()))
{
int getfile;
open = new JFileChooser();
int option = open.showOpenDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
l1.setIcon(new ImageIcon(open.getSelectedFile().getPath()));
}
}
}
}
class nbutt
{
public static void main(String args[])
{
tab x= new tab();
}
}

OUTPUT:







No comments:

Post a Comment