How to Drag and Drop a text file in new tab using swing

I want Drag and Drop a file that particular file must opened in new/separate tab.I wrote the code for DragAndDrop.But It has worked when I taken Newfile then I Drag and Drop the text File from the Computer.It has copied or override the contents of a file. But,when I Drag and drop a file,It should open in a separate tab.How can I do this.Please give me suggestions.Thank you.I have post my original application.It has two classes.

Main class:

public class OpenDemo extends javax.swing.JFrame implements ChangeListener{
  private ArrayList<OInternalFrame> frames = new ArrayList<OInternalFrame>();
  private OInternalFrame currentFrame;
  int i=0;
  JTabbedPane tabbedPane2;
  public OpenDemo() {
    initComponents();
}
@SuppressWarnings("unchecked")                        
private void initComponents() {
    tabbedPane2=new JTabbedPane();
    this.add(tabbedPane2);
    enableDragAndDrop();
    tp = new javax.swing.JTabbedPane();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    open = new javax.swing.JMenuItem();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jMenu1.setText("File");
    open.setText("Open");
    open.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            openActionPerformed(evt);
        }
    });
    jMenu1.add(open);
    jMenuBar1.add(jMenu1);
    setJMenuBar(jMenuBar1);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(tp, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE));
    pack();
}                       

private void openActionPerformed(java.awt.event.ActionEvent evt) {                                     
    FileDialog fd = new FileDialog(OpenDemo.this, "Select File", FileDialog.LOAD);
    fd.setVisible(true);
    String sts;
    if (fd.getFile() != null) {
        sts = fd.getDirectory() + fd.getFile();
        System.out.println(sts);
        BufferedReader br = null;
        StringBuffer str = new StringBuffer("");
        try {
            br = new BufferedReader(new FileReader(sts));
            String line;
            try {
                while ((line = br.readLine()) != null) {
                    str.append(line + "\n");
                }
            } catch (IOException ex) {
                Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
              }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
          }
        String t = str.toString(); 
        OInternalFrame internalFrame = new OInternalFrame("",true,true);  
        i++;
        internalFrame.setName("Doc "+i);
        try {
            internalFrame.setSelected(true);
        } catch (PropertyVetoException ex) {
            Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
          }
        internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
            @Override
            public void internalFrameClosing(InternalFrameEvent e) {
                i--;
                frames.remove(currentFrame);
                tp.remove(currentFrame);
            }
        });
        tp.add(internalFrame);
        tp.setSelectedIndex(i-1);  
        tp.addChangeListener(this);
        frames.add(internalFrame);
        currentFrame=internalFrame;

        currentFrame.setText(t);
        currentFrame.setVisible(true);
    }     
}
@Override
public void stateChanged(ChangeEvent ce) {
    JTabbedPane sourceTabbedPane = (JTabbedPane) ce.getSource();
    int index = sourceTabbedPane.getSelectedIndex();
    try {
        currentFrame =frames.get(index);
    }
    catch(IndexOutOfBoundsException e1){
    }
}
public static void main(String args[]) {
try {
    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
            javax.swing.UIManager.setLookAndFeel(info.getClassName());
            break;
        }
    }
} catch (ClassNotFoundException ex) {
    java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
        new OpenDemo().setVisible(true);
    }
  });
  }
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JTabbedPane tp;    
private void enableDragAndDrop() {
    OInternalFrame iFrame=new OInternalFrame("",true,true);
    DropTarget target=new DropTarget(currentFrame.textArea,new DropTargetListener(){
    public void dragEnter(DropTargetDragEvent e) {
    }
    public void dragExit(DropTargetEvent e) {
    }
    public void dragOver(DropTargetDragEvent e) {
    }
    public void dropActionChanged(DropTargetDragEvent e) {
    }
    public void drop(DropTargetDropEvent e) {
        try {
            e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
            java.util.List list=(java.util.List)e.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
            File file=(File)list.get(0);
            //JTextArea newTabTextArea=new JTextArea();
            //DropTarget target=new DropTarget(newTabTextArea,this);
            DropTarget target=new DropTarget(currentFrame.textArea,this);
            //newTabTextArea.read(new FileReader(file),null);
            currentFrame.textArea.read(new FileReader(file),null);
            //newTabTextArea.setCaretPosition(0);
            currentFrame.textArea.setCaretPosition(0);
            //tabbedPane2.add(add(newTabTextArea));
            tp.add(currentFrame.textArea);
            int tabIndex=tp.indexOfComponent(currentFrame.textArea);
            tp.setSelectedIndex(tabIndex);
            tp.setTitleAt(tabIndex,file.getName());
            add(tp);
        }
        catch(Exception ex){}
    }
 });
}
}

OInternalFrame :

public class OInternalFrame extends JInternalFrame
{
public JTextArea textArea;
private JScrollPane scrollPane;
JTabbedPane tabbedPane2;
public OInternalFrame(String title,boolean resizable,boolean closable)
{
    super(title,resizable,closable);
    initComponents();
}
private void initComponents() {
    textArea = new JTextArea();
    tabbedPane2=new JTabbedPane();
    scrollPane = new JScrollPane();
    textArea.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
    add(scrollPane);
    scrollPane.getViewport().add(textArea);
    setVisible(true);
    scrollPane.setVisible(true);
}
public void setText(String t) {
    textArea.setText(t);
    textArea.setCaretPosition(0);
    textArea.setVisible(true);
    textArea.repaint();
}
}

Answers


Repalce Your OpenDemo file with this code : Changes are

  • Added New internal frame for each Drop Event
  • Added Drop event listner in main frame which was missing.
  • Added Drop Listner in internal frame when it is added through Open menu item
  • Added New Internal Class for DropListner instead of anonymous class to have code reuse.
  • some minor chagnes
  • You should Debug step by step ,and you can found these issue easily.

    public class OpenDemo extends javax.swing.JFrame implements ChangeListener
    {
    private ArrayList<OInternalFrame> frames = new ArrayList<OInternalFrame>();
    private OInternalFrame currentFrame;
    private DropTargetListener dropListner;
    int i=0;
    JTabbedPane tabbedPane2;
    public OpenDemo() {
      initComponents();
    }
    @SuppressWarnings("unchecked")
    private void initComponents() {
    dropListner=new DropTargetListener();
    currentFrame=new OInternalFrame("doc1",true,true);
    tabbedPane2=new JTabbedPane();
    this.add(tabbedPane2);
    enableDragAndDrop();
    tp = new javax.swing.JTabbedPane();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    open = new javax.swing.JMenuItem();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jMenu1.setText("File");
    open.setText("Open");
    open.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            openActionPerformed(evt);
        }
    });
    jMenu1.add(open);
    jMenuBar1.add(jMenu1);
    setJMenuBar(jMenuBar1);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tp, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE));
    pack();
     }
    
    private void openActionPerformed(java.awt.event.ActionEvent evt) {
    FileDialog fd = new FileDialog(OpenDemo.this, "Select File", FileDialog.LOAD);
    fd.setVisible(true);
    String sts;
    if (fd.getFile() != null) {
        sts = fd.getDirectory() + fd.getFile();
        System.out.println(sts);
        BufferedReader br = null;
        StringBuffer str = new StringBuffer("");
        try {
            br = new BufferedReader(new FileReader(sts));
            String line;
            try {
                while ((line = br.readLine()) != null) {
                    str.append(line + "\n");
                }
            } catch (IOException ex) {
                Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
        }
        String t = str.toString();
        OInternalFrame internalFrame = new OInternalFrame("",true,true);
        i++;
        internalFrame.setName("Doc "+i);
        // Should file name here
        internalFrame.setName(fd.getFile());
        DropTarget target=new DropTarget(internalFrame.textArea,dropListner);
        try {
            internalFrame.setSelected(true);
        } catch (PropertyVetoException ex) {
            Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
        }
        internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
            @Override
            public void internalFrameClosing(InternalFrameEvent e) {
                i--;
                frames.remove(currentFrame);
                tp.remove(currentFrame);
            }
        });
        tp.add(internalFrame);
        tp.setSelectedIndex(i-1);
        tp.addChangeListener(this);
        frames.add(internalFrame);
        currentFrame=internalFrame;
    
        currentFrame.setText(t);
        currentFrame.setVisible(true);
    }
    }
    @Override
    public void stateChanged(ChangeEvent ce) {
    JTabbedPane sourceTabbedPane = (JTabbedPane) ce.getSource();
    int index = sourceTabbedPane.getSelectedIndex();
    try {
        currentFrame =frames.get(index);
    }
    catch(IndexOutOfBoundsException e1){
    }
    }
    public static void main(String args[]) {
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
     } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new OpenDemo().setVisible(true);
        }
    });
    }
     private javax.swing.JMenu jMenu1;
     private javax.swing.JMenuBar jMenuBar1;
     private javax.swing.JMenuItem open;
     private javax.swing.JTabbedPane tp;
     private void enableDragAndDrop() {
     DropTarget target=new DropTarget(this,dropListner);
     }
    
     private class DropTargetListener implements java.awt.dnd.DropTargetListener
     {
     public void dragEnter(DropTargetDragEvent e) {
     }
     public void dragExit(DropTargetEvent e) {
     }
     public void dragOver(DropTargetDragEvent e) {
     }
     public void dropActionChanged(DropTargetDragEvent e) {
     }
     public void drop(DropTargetDropEvent e) {
     try {
        e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
        java.util.List list=(java.util.List)e.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
        File file=(File)list.get(0);
        OInternalFrame newOInternalFrame=new OInternalFrame(file.getName(),true,true);
        DropTarget target=new DropTarget(newOInternalFrame.textArea,dropListner);
        newOInternalFrame.textArea.read(new FileReader(file),null);
        // currentFrame.textArea.read(new FileReader(file),null);
        newOInternalFrame.textArea.setCaretPosition(0);
        // currentFrame.textArea.setCaretPosition(0);
        //tabbedPane2.add(add(newTabTextArea));
        tp.add(newOInternalFrame);
        int tabIndex=tp.indexOfComponent(newOInternalFrame);
        tp.setSelectedIndex(tabIndex);
        tp.setTitleAt(tabIndex,file.getName());
        add(tp);
    }
    catch(Exception ex){}
    }
    }
    }
    

Image:


Use below code to open file in new tab. I have added code in Method:drop(DropTargetDropEvent e) and constructor. please use according to your need , change jframe hight and width .Reply if need any help.

import javax.swing.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.*;
import java.io.File;
import java.io.FileReader;

public class DragAndDropFile extends javax.swing.JFrame {
JScrollPane scrollPane;
JTextArea textArea;
private JTabbedPane tabbedPane2;

public DragAndDropFile() {

    //initComponents();
    textArea=new JTextArea();
    scrollPane=new JScrollPane(textArea);
    tabbedPane2=new JTabbedPane();
    this.add(tabbedPane2);
    enableDragAndDrop();

}

private void newFileActionPerformed(java.awt.event.ActionEvent evt) {

    //tabbedPane.add(scrollPane);
}

private void enableDragAndDrop() {

        DropTarget target=new DropTarget(this,new DropTargetListener(){
        public void dragEnter(DropTargetDragEvent e) {
        }
        public void dragExit(DropTargetEvent e) {
        }
        public void dragOver(DropTargetDragEvent e) {
        }
        public void dropActionChanged(DropTargetDragEvent e) {
        }
        public void drop(DropTargetDropEvent e) {
            try {
                e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                java.util.List list=(java.util.List) e.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
                File file=(File)list.get(0);

                JTextArea newTabTextArea=new JTextArea();
                DropTarget target=new DropTarget(newTabTextArea,this);
                newTabTextArea.read(new FileReader(file),null);
                newTabTextArea.setCaretPosition(0);
                tabbedPane2.add(newTabTextArea);
                int tabIndex=tabbedPane2.indexOfComponent(newTabTextArea);
                tabbedPane2.setSelectedIndex(tabIndex);
                tabbedPane2.setTitleAt(tabIndex,file.getName());


            }
            catch(Exception ex){}
        }
    });
}

public static void main(String args[]) {
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info :  javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(DragAndDropFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(DragAndDropFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(DragAndDropFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(DragAndDropFile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new DragAndDropFile().setVisible(true);
        }
    });
}
private javax.swing.JMenu file;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem newFile;
private javax.swing.JTabbedPane tabbedPane;

}

Answer to your integration issue.

  1. You have to create new text area each time you drap a file because you want them in separate tab so change your drop method drop in OInternalFrame with below

    public void drop(DropTargetDropEvent e) {
    try {
        e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
        java.util.List list=(java.util.List)e.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
        File file=(File)list.get(0);
        JTextArea newTabTextArea=new JTextArea();
        DropTarget target=new DropTarget(newTabTextArea,this);
        newTabTextArea.read(new FileReader(file),null);
        newTabTextArea.setCaretPosition(0);
        tabbedPane2.add(add(newTabTextArea));
        int tabIndex=tabbedPane2.indexOfComponent(newTabTextArea);
        tabbedPane2.setSelectedIndex(tabIndex);
        tabbedPane2.setTitleAt(tabIndex,file.getName());
    }
    catch(Exception ex){}
    

    }

  2. You have not add tabbedpane2 in you frames . According to your code it look like your are planning to add in Internal frame. But i suggest to add drop listener in OpenDemo frame it will look good but depends on your requirement.add below line in initComponents method

    this.add(tabbedPane2);
    
  3. After this it will work when you add file from menu item (first file is not visible you should work on that). then once internal frame is added you can drag and drop file you needed.

4.I suggest to have tabbedpane2 and drop listener in main frame ie openDemo and remove internal frame but depends on your design.

see screen shot.


Need Your Help

jQuery rewriting src attribute on script tag dynamically written onto page (adding timestamp, prevents use of browser cache)

jquery

I'm using jQuery's .prepend(), .html(), and .after() functions to write HTML on to my page. This includes a tag to a static JavaScript file.

Jquery form : success callback called whereas form not submitted

jquery forms

I get a script that creates a form with an input file after clicking on a link, but when I load the function creating the form, the success callback is immediatly called. Did you get the same probl...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.