ボーダーレイアウトのJpanelに複数のDnDパネルを重ねています。各DnDパネルには、ドロップターゲットとして設定されたテキストフィールドがあります。最後のDnDパネルのみがフォーカスを取得します。その他はドロップターゲットとして機能しません。これがDnDパネルのコードです
public class DnDPanel extends javax.swing.JPanel {
/** Creates new form DnDPanel */
public DnDPanel() {
initComponents();
dndTextField.setDropTarget(new DropTarget() {
@Override
public synchronized void drop(DropTargetDropEvent evt) {
try {
dndTextField.setBackground(Color.WHITE);
evt.acceptDrop(DnDConstants.ACTION_COPY);
List<File> droppedFiles = (List<File>) evt.getTransferable().getTransferData(
DataFlavor.javaFileListFlavor);
for (File file : droppedFiles) {
dndTextField.setText(file.getAbsolutePath());
}
dndTextField.setBackground(Color.getHSBColor(0.56f, 1.0f, 0.9f));
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public synchronized void dragEnter(DropTargetDragEvent dtde) {
//Change cursor...
Cursor cursor = new Cursor(Cursor.HAND_CURSOR);
setCursor(cursor);
dndTextField.setText("Drop Here !!");
dndTextField.setBackground(Color.getHSBColor(0.56f, 1.0f, 0.9f));
}
@Override
public synchronized void dragExit(DropTargetEvent dtde) {
Cursor cursor = new Cursor(Cursor.DEFAULT_CURSOR);
setCursor(cursor);
dndTextField.setBackground(Color.WHITE);
dndTextField.setText("Drag n drop a Folder");
}
});
}
public static void setText(String text)
{
dndTextField.setText(text);
}
public static String getPath()
{
return dndTextField.getText();
}
/** 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() {
dndTextField = new javax.swing.JTextField();
setPreferredSize(new java.awt.Dimension(250, 250));
dndTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
dndTextField.setText("DnD");
dndTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dndTextFieldActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(dndTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(dndTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>
private void dndTextFieldActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
// Variables declaration - do not modify
private static javax.swing.JTextField dndTextField;
// End of variables declaration
}