Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


prathima
swings
2 Answer(s)      5 years and a month ago
Posted in : Java Beginners



Advertisement
View Answers

December 14, 2009 at 12:33 PM


Hello 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");
Action insertAction = new InsertAction("Insert");

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.getActionMap().put("insertAction",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);
buttons.add(uploadButton);
addButton = new JButton(browseAction);
removeButton = new JButton(insertAction);
buttons.add(removeButton);
buttons.add(addButton);
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)"; }
}
class UploadAction extends AbstractAction {
public UploadAction(String text) { super(text); }
public void actionPerformed(ActionEvent evt) {
System.out.println(evt.getActionCommand());
}
}


December 14, 2009 at 12:33 PM


continue..

class InsertAction extends AbstractAction {
public InsertAction(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{
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";;
String db = "test";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
FileInputStream fis;
Class.forName(driver);

con = DriverManager.getConnection(url+db, user, pass);
PreparedStatement st = con.prepareStatement("insert into file(file,file_data) values(?,?)");
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:
SWINGS
SWINGS  WHAT ARE THE DIFFERENCES BETWEEN AWT AND SWINGS
JSP & Swings
JSP & Swings  How to integrate jsp and swings
Advertisements
swings question
swings question  how to change the background color with the help of color values by using swings
swings for webnms
swings for webnms  if i am expanding node of jtree then i want to collapse previous expanding node of jtree in swings how is it possible
Swings JTable
Swings JTable  add values to JTable with four coloums,two of them are comboboxes
Swings & JSP
Swings & JSP  Hai all, Can we use Swing components in a JSP?? Suppose if we enter details in a swing dialog box..and If we want the result in a JSP..is that possible??? Thank you
Java Swings
Java Swings  I am doing one project on java Swings, in this i have created one jframe where i defined some JButtons and Jcombobox's, here i need to insert one JTable with headers(IN CURRENT JFrame only).pls help me urgently
swings header
swings header   have a string1 it contains 3 parts,for example "123456 service hello" and string2 contains text "change request " like this. and the string3 should contain "123456 +(second string)+ hello" "second string can
swings
","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}; for(i = 0
Swings and JDBC
Swings and JDBC  Hi.. I am vinay.. I am developing a small application using swings and mysql. I am sending part of the code here.. The problem is i need to update the mysql fields with values which are gettin from dynamiclly
Swings - Applet
Swings  Sir, I have developed an application in swings i want to call that class in applet. is it possible. or otherwise is there any way to deploy java class in browser. Give an example... Thanks in advance...  Hi
how to create frame in swings
how to create frame in swings  how to create frame in swings
Image Movement using Swings
Image Movement using Swings  How to move image using Swings
java swings - Java Beginners
java swings   Do you want to add textfields on the JPanel
Swings/awt - Swing AWT
Swings/awt  Hi, how to write action listeners to the Buttons in RichTextEditor tool bar.. thanks in advance...it's Urgent... i am very much new to Swings
java code using swings
java code using swings  code that should be able to enter data of student details using all swings into the access database using jdbc connectivity
java swings - Java Beginners
java swings   Hi, I need the code for click the refresh button then list values will be refresh.Please send the code ........... Thanks, Valarmathi
An application using swings and vector methods
An application using swings and vector methods   Hi, I want an application in Java swings which uses good selection of Vectors methods
about swings - Java Beginners
about swings   Dear sir,Good evening, i am doing mca sir,i am doing the project in swings,so plz provide the material about swings sir Thank you  Hi Friend, Please visit the following link
java swings - Java Beginners
java swings   Hi, I need the code for joptionpane with jcombobox. my requirement is click on add button,one joptionpane will come.from the option pane i need to select the combobox values. Please send the sample code
swings window header
swings window header  i have a string1 it contains 3 parts,for example "123456 service hello" and string2 contains "change request " like this. and the string3 should contain "123456 "........." hello" ".........." can
java swings - Swing AWT
java swings  I am doing a project for my company. I need a to show the performance of the employees by using bar bharts. Please give me how can we write the code for bar charts using java swings.  Hi friend, I am
another frame by using awt or swings
another frame by using awt or swings  how to connect one frame to another frame by using awt or swings
making of dynamic textfields using swings
making of dynamic textfields using swings  How to make dynamic textfields using java swings
how can we store the encrypted passwaord in swings?
how can we store the encrypted passwaord in swings?   how can we store the encrypted passwaord in swings
Advertisements
 

 

 

DMCA.com