?
Solved

Java expert help needed - Code attached

Posted on 2011-09-07
11
Medium Priority
?
370 Views
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.

Regards,
Sree
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);
            panel.add(button_2,gbc_2);
		        
            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;
            panel.add(button_Extract,gbc_3);
            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";
                    try{
                       // 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(buff.charAt(31));

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

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

                            }

                            if(reading){
                                 if(buff.charAt(31)== 'I')psout.println(buff);
                                continue;
                            }



                        }
showDialog("File extraction is success " );
                          r.close();
                        System.exit(0);


                    } catch(Exception ex){
                        ex.printStackTrace();
                    }
                }
             }) ;
            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.setText(c.getSelectedFile().getAbsolutePath());
              //    textField_2.setText(c.getCurrentDirectory().toString());
                  text_1 = textField.getText();
                  text_2 = textField_2.getText();
                  System.out.print("textField" + textField.getText());
              }
                }

                 if(e.getSource().equals(button_2)){
                        JFileChooser c1 = new JFileChooser();
                     c1.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                     rVal = c1.showOpenDialog(TextAcceleratorExample.this);
                     if (rVal == JFileChooser.APPROVE_OPTION) {
                      textField_2.setText(c1.getSelectedFile().getAbsolutePath());
                     }
                 }

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

        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           // f.add();
            f.add(new TextAcceleratorExample().getContent());
            f.setSize(400,200);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setTitle("SIGNAL EXTRACTOR");
            f.setVisible(true);
        }
        private void showDialog(String s){
            JOptionPane.showMessageDialog(this, s, "Button says: ", JOptionPane.PLAIN_MESSAGE);
        }

		
}

Open in new window

0
Comment
Question by:Sreejith22
[X]
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
11 Comments
 
LVL 47

Expert Comment

by:for_yan
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.
0
 
LVL 3

Expert Comment

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

0
 
LVL 47

Expert Comment

by:for_yan
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
0
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

by:Sreejith22
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.
0
 
LVL 47

Expert Comment

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

Waht is your OS ?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36500729
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36500741
0
 

Author Comment

by:Sreejith22
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
0
 
LVL 47

Accepted Solution

by:
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() {
        initComponents();
           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.setVisible(true);
    }

    /** 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.
     */
    @SuppressWarnings("unchecked")
    // <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);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
         getContentPane().setLayout(new java.awt.GridLayout(2,1));
         getContentPane().add(jtxt1);
          getContentPane().add(jtxt2);

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

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

        jScrollPane1.setViewportView(list);

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


        pack();
    }// </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();
        evt.acceptDrop(action);
        try {
            Transferable data = evt.getTransferable();
            if (data.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                List<File> files = (List<File>) data.getTransferData(
                        DataFlavor.javaFileListFlavor);
                for (File file : files) {
                    jtxt1.setText(file.getAbsolutePath());
                  //  listModel.addElement(file);
                }
            }
        } catch (UnsupportedFlavorException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            evt.dropComplete(true);
        }


    }

    private class FileTransferHandler extends TransferHandler {

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

        @Override
        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

0
 

Author Comment

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

Expert Comment

by:for_yan
ID: 36500876
see code above
0

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