Java Program

Java Program

Write a Program that display JFileChooser that open a JPG Image and After Loading it Saves that Image using JFileChooser
View Answers

March 9, 2010 at 11:55 AM

Hi Friend,

Try the following code:

import java.io.*;
import java.sql.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.dnd.*;
import java.awt.datatransfer.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.filechooser.*;

public class Uploader extends JFrame {
public static JFrame frame;
public JList list;
public DefaultListModel model;
public File currentDir;
public DropTarget target;
JButton addButton, removeButton, uploadButton;
public Uploader() {
setSize(600,400);
setResizable(true);
setLocation(100,100);

Action uploadAction = new UploadAction("Upload");
Action browseAction = new BrowseAction("Browse");
JPanel cp = new JPanel();
cp.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
cp.setLayout(new BorderLayout());

setContentPane(cp);
model = new DefaultListModel();
list = new JList(model);
list.getInputMap().put(KeyStroke.getKeyStroke(8,0),"insertAction");
list.setVisibleRowCount(12);
list.setCellRenderer(new ImageCellRenderer());

target = new DropTarget(list,new FileDropTargetListener());
cp.add(new JScrollPane(list),BorderLayout.CENTER);
JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout(FlowLayout.RIGHT,5,10));
JLabel uploadLabel = new JLabel();
uploadLabel.setLayout(new FlowLayout(FlowLayout.LEFT,5,10));
uploadButton = new JButton(uploadAction);
uploadLabel.add(uploadButton);
addButton = new JButton(browseAction);
buttons.add(addButton);
buttons.add(uploadButton);
cp.add(buttons,BorderLayout.SOUTH);
currentDir = new File(System.getProperty("user.dir"));
}
public int addToListModel(ArrayList filenames) {
int count = 0;
for ( Iterator i = filenames.iterator(); i.hasNext(); ) {
String filename = (String)i.next();
if (!model.contains(filename)) {
model.addElement(filename);
count++;
}
}
return count;
}
public static void main(String [] args) {
frame = new Uploader();
frame.setVisible(true);
}
class BrowseAction extends AbstractAction {
public BrowseAction(String text) { super(text); }

public void actionPerformed(ActionEvent evt) {
JFileChooser chooser = new JFileChooser(currentDir);
chooser.addChoosableFileFilter(new ImageFileFilter());
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setMultiSelectionEnabled(true);
chooser.setDragEnabled(true);
chooser.showOpenDialog(frame);
currentDir = chooser.getCurrentDirectory();
File [] files = chooser.getSelectedFiles();
ArrayList filenames = new ArrayList(files.length);
for (int i = 0; i < files.length; i++)
filenames.add(files[i].getName());
addToListModel(filenames);
}
}
class ImageFileFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
if (file.isDirectory()) return false;
String name = file.getName().toLowerCase();
return (name.endsWith(".jpg") || name.endsWith(".png")|| name.endsWith(".gif"));
}
public String getDescription() { return "Images ( *.jpg, *.png,*.gif)"; }
}

March 9, 2010 at 11:56 AM

continue..

class UploadAction extends AbstractAction {
public UploadAction(String text) { super(text); }
public void actionPerformed(ActionEvent evt) {
int selected = list.getSelectedIndex();
Object ob=null;
ob=model.getElementAt(selected);
String fileName=ob.toString();
File file=new File(fileName);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test";, "root", "root");
PreparedStatement st = con.prepareStatement("insert into file(file,file_data) values(?,?)");
FileInputStream fis = new FileInputStream(file);
st.setString(1,fileName);
st.setBinaryStream(2, (InputStream)fis, (int)(file.length()));
int s = st.executeUpdate();
JOptionPane.showMessageDialog(null,"image is successfully uploaded and inserted.");
}
catch(Exception ex){}
}
}
class ImageCellRenderer extends JLabel implements ListCellRenderer {
public ImageCellRenderer() {
setOpaque(true);
setIconTextGap(12);
}
public Component getListCellRendererComponent(JList list,Object value,int index,boolean isSelected,boolean cellHasFocus){
File f = new File(value.toString());
Border empty = BorderFactory.createEmptyBorder(3,3,3,3);
Border matte = BorderFactory.createMatteBorder(0,0,1,0,Color.white);
setBorder(BorderFactory.createCompoundBorder(matte,empty));
setText(f.getName());
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image icon = toolkit.getImage(f.getPath());
Image scaledIcon = icon.getScaledInstance(40,40,Image.SCALE_FAST);
setIcon(new ImageIcon(scaledIcon));
if (isSelected) {
setBackground(new Color(61,128,223));
setForeground(Color.white);
} else if (index % 2 == 0) {
setBackground(new Color(237,243,254));
setForeground(Color.darkGray);
} else {
setBackground(Color.white);
setForeground(Color.darkGray);
}
return this;
}
}
class FileDropTargetListener extends DropTargetAdapter {
public void dragEnter(DropTargetDragEvent evt) {
frame.requestFocusInWindow();
}
public void drop(DropTargetDropEvent evt) {
try {
Transferable tr = evt.getTransferable();
DataFlavor [] flavors = tr.getTransferDataFlavors();
for ( int i = 0; i < flavors.length; i++ ) {
if ( flavors[i].isFlavorJavaFileListType() ) {
evt.acceptDrop(DnDConstants.ACTION_COPY);
java.util.List list2 = (java.util.List)tr.getTransferData(flavors[i]);
ArrayList filenames = new ArrayList();
for ( int j = 0; j < list2.size(); j++ ) {
String path = list2.get(j).toString();
if ( ((new ImageFileFilter()).accept(new File(path))) ) {
filenames.add(path);
}
}
if (filenames.size() > 0 ) {
int numAdded = addToListModel(filenames);
evt.dropComplete(true);
return;
}
}
JOptionPane.showMessageDialog(frame,"Error","Invalid File Type",JOptionPane.WARNING_MESSAGE);
evt.rejectDrop();
}

} catch (Exception e) {
e.printStackTrace();
evt.rejectDrop();
}
}
}
}

Thanks









Related Tutorials/Questions & Answers:
java program for
java program for   java program for printing documents,images and cards
a Java program
a Java program    Write a Java program to print even numbers from 2 to 1024? Write a Java program to print ? My Name is Mirza? 100 times? Write a Java program to print Fibonacci Series? Write a Java program to reverse a number
Advertisements
Java Program
Java Program  A Java Program that print the data on the printer but buttons not to be printed
java program
java program  write a program to print 1234 567 89 10
java program
java program  Write a program to demonstrate the concept of various possible exceptions arising in a Java Program and the ways to handle them.  ... in Java
java program
java program  write java program for constructor,overriding,overriding,exception handling
java program
java program  how to write an addition program in java without using arithematic operator
java program
java program  write a java program to display array list and calculate the average of given array
java program
java program  write a java program to display array list and calculate the average of given array
Java Program
Java Program  java program to insert row in excel sheet after identifying an object
java program
java program  java program to implement the reflection of a particular class details like constructor,methods and fields with its modifiers
java program
java program  Write a java program to do matrix addition operation On two given matrices
java program
java program  Write a java program to find the number of Positive numbers in m* n matrix
java program
java program  Write a program to create an applet and display The message "welcome to java
java program
java program  hi friends how to make a java program for getting non prime odd numbers in a given series
java program
java program   Write a program to find the difference between sum of the squares and the square of the sums of n numbers
java program
java program  write a program to create text area and display the various mouse handling events
java program
java program  Develop the program calculatePipeArea. It computes the surface area of a pipe, which is an open cylinder. The program accpets three values: the pipes inner radius, its length, and the thickness of its wall
java program
java program  . Develop the program calculatePipeArea. It computes the surface area of a pipe, which is an open cylinder. The program accpets three values: the pipes inner radius, its length, and the thickness of its wall
java program
java program  . Write a program which performs to raise a number to a power and returns the value. Provide a behavior to the program so as to accept any type of numeric values and returns the results
Java program
Java program  Write a program which performs to raise a number to a power and returns the value. Provide a behavior to the program so as to accept any type of numeric values and returns the results
program in java
program in java  write a reverse program in java using string buffer.the input and out put as follows. input- hi good mornig out put-ih doog ginrom
java program
java program  write a java program to compute area of a circle.square,rectangle.triangle,volume of a sphere ,cylinder and perimeter of cube using method over riding
java program
java program  write a java program to compute area of a circle.square,rectangle.triangle,volume of a sphere ,cylinder and perimeter of cube using method over riding
java program
java program   A B C D E F F E D C B A A B C D E E D C B A A B C D D C B A A B C C B A A B B A A A java program to display above triangle
java program
java program  write a program to create server and client such that server receives data from client using BuuferedReader and sends reply to client using PrintStream
java program
java program  write a program to read 10 numbers from user and store it in a array. display the maximum n minimum number in the array
java program
java program  write a java program to read a file which hold email address validate email address tohave formate @.* and replace all .com email address
java program
java program  write a java program to create an array of size 10 by taking input from bufferreader and find out the average of array elements from that array
java program
java program  write a java program to create an array of size 10 by taking input from bufferreader and find out the average of array elements from that array
java program
java program  write a java program to create an array of size 10 by taking input from bufferreader and find out the average of array elements from that array
Java Program
Java Program  I want to Write a program in JAVA to display to create a class called MATRIX using a two-dimensional array of integers. Perform the addition and subtraction of two matrices. Help me
java program
java program  i want a applet program that accepts two input strings using tag and concatenate the strings and display it in status window. please give mi he code for this in core java
java program
java program  i want a applet program that accepts two input strings using tag and concatenate the strings and display it in status window. please give mi he code for this in core java
java program
java program  i want a applet program that accepts two input strings using tag and concatenate the strings and display it in status window. please give mi he code for this in core java
java program
java program  Write a program that computes loan payments. The loan can be a car loan, a student loan, or a home mortgage loan. The program lets the user enter the interest rate, number of years, loan amount, and displays
java program
java program  . Develop a program that computes the distance a boat travels across a river, given the width of the river, the boat's speed perpendicular to the river, and the river's speed. Speed is distance/time
java program
java program  write a program that accepts only 3 integer values as command line arguments.print the values enter by the user. handle ArrayIndexOutofbounds exception and number format exception by providing appropriate message
java program
java program  write a program showing two threads working simultanously upon two objects(in theater one object "cut the ticket" andsecond object "show is the seat
A java Program
A java Program  Write a java program, which provides a text area with horizontal and vertical scrollbar.Type some lines in the text area and use scrollbars to move the text within the text area.Read a word in a text field
java program
java program  write a java program to display the following output. [email protected] 1] Symbol @ cannot come for first letter 2] @ symbol only come at one time. 3] .com should be come for after the mail id
a java program
a java program  Write a java program that accepts positive numbers... through the link may, this will be helpful for you http://www.roseindia.net/java/thread/java-multithreading-example.shtml Thanks
java program
java program  Develop the program calculateHeight, which computes the height that a rocket reaches in a given amount of time. If the rocket accelerates at a constant rate g, it reaches a speed of g â?¢ t in t time units
java program
java program  Develop the program calculateHeight, which computes the height that a rocket reaches in a given amount of time. If the rocket accelerates at a constant rate g, it reaches a speed of g ? t in t time units
java program
java program  Hi, can any one solve this program for me. Q.In a knock-out tennis tournament(Singles). (A)N players participate. (B)construct a data structure to represent the results optimized to find the winners. (C
Java Program
Java Program  Write a Java program so that when the program is executed, a window will appear with white background. The window should be of size 400x400 pixels. Then when the user clicks at the window, a circle of size 20
Java Program
Java Program  Write a Java program so that when the program is executed, a window will appear with white background. The window should be of size 400x400 pixels. Then when the user clicks at the window, a circle of size 20
java program
java program  write a java program which shows how to declare and use STATIC member variable inside a java class.   The static variable are the class variables that can be used without any reference of class. class
java program
java program  write a java program to read a file content into a string object using available and read methods of java bufferedinputstream.   Please visit the following link: http://www.roseindia.net/java/example/java
java program
java program  write a java script program that would input the ff... and below no discount   write a java script program that would...% 84 and below no discount   write a java script program

Ads