윈도우 탐색기에서 마우스로 파일을 선택하여 프로그램으로 드래그하는 것으로 파일을 읽는 것을 Drag and Drop 라고 한다. 간단하게 구현 방법을 알아보자.
DropTarget
public DropTarget(Component c, DropTargetListener dtl)
드래그 앤 드롭을 적용할 Component와 드롭되었을 때 적절한 처리를 해줄 DropTargetListener를 생성자 파라미터로 받는다.
DropTargetListener
Method | 설명 |
public void drop(DropTargetDropEvent dtde) | 파일이 드래그 된 후 타겟 위에서 마우스 동작을 종료했을 때 호출 |
public void dragEnter(DropTargetDragEvent dtde) | 파일이 타겟 위에 드래그 된 시점에서 호출 |
public void dragOver(DropTargetDragEvent dtde) | 파일이 드래그 된 후 타겟 위에서 마우스 포인터가 존재할 때 호출 |
public void dropActionChanged(DropTargetDragEvent dtde) | 파일이 드래그 된 후 제스쳐가 변경되었을 때 호출 |
public void dragExit(DropTargetEvent dte) | 파일이 드래그 된 상태에서 포인터가 타겟에서 벗어났을 때 호출 |
드래그 앤 드롭 과정에서 발생하는 콜백 메서드들이다. 다른 메서드는 그다지 쓰이지 않고 drop을 구현하는 것이 일반적이다.
Code
import java.awt.Color;
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.DnDConstants;
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.util.List;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class GUI extends JFrame implements DropTargetListener{
JTextArea jta_log;
public GUI () {
setTitle("Swing");
setBounds(10, 10, 400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(Color.gray);
setLayout(null);
DropTarget dropTarget = new DropTarget(this, this);
setDropTarget(dropTarget);
jta_log = new JTextArea();
jta_log.setBounds(10, 10, 360, 200);
add(jta_log);
}
@Override
public void drop(DropTargetDropEvent dtde) {
jta_log.append("파일이 드롭되었습니다.\n\n");
try {
dtde.acceptDrop(DnDConstants.ACTION_MOVE);
List<File> files = (List<File>)dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
for(File file : files) {
jta_log.append(file.getPath() + "\n");
}
} catch(Exception e) {
e.printStackTrace();
}
}
@Override
public void dragEnter(DropTargetDragEvent dtde) { }
@Override
public void dragOver(DropTargetDragEvent dtde) { }
@Override
public void dropActionChanged(DropTargetDragEvent dtde) { }
@Override
public void dragExit(DropTargetEvent dte) { }
}
예제는 JTextArea를 배치하여 드롭된 파일 목록을 출력한다. DropTargetListener는 이름에서 짐작할 수 있듯이 파일을 드래그해 올 때 이벤트를 감지하고 처리하는 인터페이스이고, DropTarget은 파일을 드롭시킬 Target Component와 이벤트를 설정할 수 있다. JFrame을 Target으로 하고 이벤트도 현재 클래스에서 implements 했으므로 (this, this)를 넘겨주었다.
파일을 Drop하게 되면 Drop 메서드에서 File 타입 객체들을 List로 읽어올 수 있다. 바로 처리할 것이 아니라면 File 타입의 리스트를 멤버 변수로 생성해두고 파일이 드래그될 때마다 누적시켜서 처리하는 것이 좋다.
'자바 > Swing' 카테고리의 다른 글
[Java/Swing] JOptionPane 아이콘 커스텀하기 (0) | 2022.12.05 |
---|---|
[Java/Swing] JTable에서 선택된 값 클립보드에 복사하기 (0) | 2022.12.03 |
[Java/Swing] 화면에 컴포넌트가 보이지 않을 때 (0) | 2021.12.02 |