Java expert help needed - Code attached

Posted on 2011-09-07
Medium Priority
Last Modified: 2012-05-12
Hi experts,

Please find attached the file which can be run to view the output. When you view the output, you can notice two text fields and a browse button corresponding to each text field. I need to modify this in such a way that, I do not want to browse and find the input file, instead I just need to drag and drop a file to this textfield, such that, the file path comes there. Also, I should have the option to type the path of the file.
Any help in this regard which provides me the perfect solution would be much appreciated with points.

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class TextAcceleratorExample extends JFrame{
       JTextField textField = new JTextField(50);
       JTextField textField_2 = new JTextField(50);
       JButton button_Extract = new JButton("Extract");
       JButton button_Cancel = new JButton("Cancel");
       String text_1 ;
       String text_2;
     JButton button;
     JButton button_2;
     private JPanel getContent() {
            // Try changing columns argument.
             button = new JButton("Browse");
             button_2 = new JButton("Browse");
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc= new GridBagConstraints();
            gbc.insets = new Insets(5,15,5,0);
            gbc.weightx = 1.0;
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.anchor = GridBagConstraints.CENTER;
            panel.add(new JLabel("Enter Input Path  : "), gbc);
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1.0;
            gbc.gridx = 1;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.FIRST_LINE_END;
            gbc.insets = new Insets(10,0,5,5);
            //textField.setPreferredSize(new Dimension(100,20));
            panel.add(textField, gbc);
            gbc.fill = GridBagConstraints.NONE;
            gbc.anchor = GridBagConstraints.WEST;
            button.addActionListener(new OpenL());
            gbc.gridx = 2;
            gbc.gridy = 0;
            gbc.insets = new Insets(5,5,5,5);
            panel.add(button, gbc);
            GridBagConstraints gbc_2 = new GridBagConstraints();
            gbc.insets = new Insets(5,15,5,0);
            gbc_2.weightx = 1.0;
            gbc_2.gridy = 1;
            gbc_2.gridx = 0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.anchor = GridBagConstraints.CENTER;
            panel.add(new JLabel("Enter Output Path : "), gbc_2);
            gbc_2.fill = GridBagConstraints.HORIZONTAL;
            gbc.insets = new Insets(10,0,5,5);
            gbc.weightx = 1.0;
            gbc_2.gridx = 1;
            gbc_2.gridy = 1;
            gbc.anchor = GridBagConstraints.WEST;
           // textField_2.setPreferredSize(new Dimension(100,20));
            panel.add(textField_2, gbc_2);
            gbc_2.fill = GridBagConstraints.NONE;
            gbc_2.anchor = GridBagConstraints.EAST;
            button_2.addActionListener(new OpenL());
            gbc_2.gridx = 2;
            gbc_2.gridy = 1;
            gbc_2.insets = new Insets(5,5,5,5);
            GridBagConstraints gbc_3 = new GridBagConstraints();
            gbc_3.insets = new Insets(3,3,10,30);
            gbc_3.weightx = 1.0;
            gbc_3.gridy = 4;
            gbc_3.gridx = 1;
            gbc_3.fill = GridBagConstraints.VERTICAL;
            gbc_3.anchor = GridBagConstraints.CENTER;
            button_Extract.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                   // showDialog("Extract");

                    String fileInput = textField.getText();
                    String fileOutput = textField_2.getText() + System.getProperty("file.separator") + "hci_final.log";
                       // DataInputStream in = new DataInputStream(new FileInputStream(fileInput));
                        PrintStream psout = new PrintStream(new FileOutputStream(fileOutput));
                        BufferedReader r = new BufferedReader(new FileReader(fileInput));
                        String buff = null;
                        boolean reading = false;
                        int count = 0;

                        while((buff=r.readLine()) != null){
                                       if(buff.trim().length() == 0)continue;
                            System.out.println (count + "  I: " + buff.indexOf(" I "));
                             System.out.println (count + "  D: " + buff.indexOf(" D "));

                           // System.out.println(count + ": " + buff);

                            if((buff.indexOf("SENT")> -1) ||buff.indexOf("RCVD") > -1 && (reading == false)){
                                reading = true;
                                if(buff.charAt(31)== 'I')psout.println(buff);
                            if(buff.indexOf("--") > -1 && reading == true){
                                reading = false;
                                  if(buff.charAt(31)== 'I')psout.println(buff);


                                 if(buff.charAt(31)== 'I')psout.println(buff);

showDialog("File extraction is success " );

                    } catch(Exception ex){
             }) ;
            return panel;
     class OpenL implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                int rVal = -1;
                if(e.getSource().equals(button)) {
              JFileChooser c = new JFileChooser();
              // Demonstrate "Open" dialog:
              rVal = c.showOpenDialog(TextAcceleratorExample.this);
              if (rVal == JFileChooser.APPROVE_OPTION) {
              //    textField_2.setText(c.getCurrentDirectory().toString());
                  text_1 = textField.getText();
                  text_2 = textField_2.getText();
                  System.out.print("textField" + textField.getText());

                        JFileChooser c1 = new JFileChooser();
                     rVal = c1.showOpenDialog(TextAcceleratorExample.this);
                     if (rVal == JFileChooser.APPROVE_OPTION) {

              if (rVal == JFileChooser.CANCEL_OPTION) {
                  textField.setText("You pressed cancel");

        public static void main(String[] args) {
            JFrame f = new JFrame();
           // f.add();
            f.add(new TextAcceleratorExample().getContent());
            f.setTitle("SIGNAL EXTRACTOR");
        private void showDialog(String s){
            JOptionPane.showMessageDialog(this, s, "Button says: ", JOptionPane.PLAIN_MESSAGE);


Open in new window

Question by:Sreejith22
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 3
LVL 47

Expert Comment

ID: 36500672

There is no problem with typing file path in the textfiled - what kind of doubts you have on this subject - just type, and
then use getText() method and use the string whicvh you get as a file name

As to drag the file - do you mean you want to drag the file from outside your java application - say from Windows
folder window? That seems problematic to me.

Expert Comment

ID: 36500698
well drag and drop for swing elements is posible, but not really "easy"  there is a complete tutorial here, check it out,

LVL 47

Expert Comment

ID: 36500711
Drag and Drop is possible fomr one java component to another - but from system window to java application - well, everything is possible
but it is problematic. You can probably do something through clipboard, but direct drag into Java window from say your desktop
seesm difficult
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Author Comment

ID: 36500719
>>As to drag the file - do you mean you want to drag the file from outside your java application - say from Windows folder window?

Yes, I want to drag file and drop it inside textfield, so that, the path comes there automatically.
LVL 47

Expert Comment

ID: 36500722
But you want to take the file say, from your desktop, or from say JFileChooser window?

Waht is your OS ?
LVL 47

Expert Comment

ID: 36500729
LVL 47

Expert Comment

ID: 36500741

Author Comment

ID: 36500781
>>But you want to take the file say, from your desktop, or from say JFileChooser window?

Destop or from any other Windows folder
LVL 47

Accepted Solution

for_yan earned 1000 total points
ID: 36500846

Actually indeed it works - try to compile
it and drag some file to the upper textfield -
it shows the path there.

Then start form this code and add your buttons and functionality -
that qwould be really straigthforward

package dnd;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

public class DnDFrame extends javax.swing.JFrame implements DropTargetListener {

    private DefaultListModel listModel = new DefaultListModel();
    private DropTarget dropTarget1;
       private DropTarget dropTarget2;

    /** Creates new form DnDFrame */
    public DnDFrame() {
           dropTarget1 = new DropTarget(jtxt1, this);
        //  dropTarget2 = new DropTarget(jtxt2, this);

       // dropTarget = new DropTarget(list, this);
     //   list.setModel(listModel);
      //  list.setDragEnabled(true);
      //  list.setTransferHandler(new FileTransferHandler());
        jtxt1.setTransferHandler(new FileTransferHandler());
          //jtxt2.setTransferHandler(new FileTransferHandler());


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        list = new javax.swing.JList();
        jtxt1 = new JTextField(20);
        jtxt2 = new JTextField(20);

         getContentPane().setLayout(new java.awt.GridLayout(2,1));

        getContentPane().setLayout(new java.awt.GridBagLayout());

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        getContentPane().add(jLabel1, gridBagConstraints);


        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        getContentPane().add(jScrollPane1, gridBagConstraints);

    }// </editor-fold>
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList list;
      private javax.swing.JTextField jtxt1;
     private javax.swing.JTextField jtxt2;

    // End of variables declaration

    public void dragEnter(DropTargetDragEvent arg0) {
        // nothing

    public void dragOver(DropTargetDragEvent arg0) {
        // nothing

    public void dropActionChanged(DropTargetDragEvent arg0) {
        // nothing

    public void dragExit(DropTargetEvent arg0) {
        // nothing

    public void drop(DropTargetDropEvent evt) {
        int action = evt.getDropAction();
        try {
            Transferable data = evt.getTransferable();
            if (data.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                List<File> files = (List<File>) data.getTransferData(
                for (File file : files) {
                  //  listModel.addElement(file);
        } catch (UnsupportedFlavorException e) {
        } catch (IOException e) {
        } finally {


    private class FileTransferHandler extends TransferHandler {

        protected Transferable createTransferable(JComponent c) {
            JList list = (JList) c;
            List<File> files = new ArrayList<File>();
            for (Object obj: list.getSelectedValues()) {
            return new FileTransferable(files);

        public int getSourceActions(JComponent c) {
            return MOVE;

    private class FileTransferable implements Transferable {

        private List<File> files;

        public FileTransferable(List<File> files) {
            this.files = files;

        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[]{DataFlavor.javaFileListFlavor};

        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return flavor.equals(DataFlavor.javaFileListFlavor);

        public Object getTransferData(DataFlavor flavor)
                throws UnsupportedFlavorException, IOException {
            if (!isDataFlavorSupported(flavor)) {
                throw new UnsupportedFlavorException(flavor);
            return files;

    public static void main(String[] args) {
        new DnDFrame();

Open in new window


Author Comment

ID: 36500848
pls, any code snippet which would prove to be an apt solution is much appreciated.
LVL 47

Expert Comment

ID: 36500876
see code above

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Suggested Courses
Course of the Month9 days, 19 hours left to enroll

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question