From 79f55597c9edd1afd0d2197f17e78022a1f85ee7 Mon Sep 17 00:00:00 2001 From: kske Date: Wed, 14 Aug 2019 20:17:28 +0200 Subject: [PATCH] Added drag and drop support for FEN files --- src/dev/kske/chess/ui/FENDropTarget.java | 50 ++++++++++++++++++++++++ src/dev/kske/chess/ui/MainWindow.java | 3 ++ 2 files changed, 53 insertions(+) create mode 100644 src/dev/kske/chess/ui/FENDropTarget.java diff --git a/src/dev/kske/chess/ui/FENDropTarget.java b/src/dev/kske/chess/ui/FENDropTarget.java new file mode 100644 index 0000000..4d01bf5 --- /dev/null +++ b/src/dev/kske/chess/ui/FENDropTarget.java @@ -0,0 +1,50 @@ +package dev.kske.chess.ui; + +import java.awt.datatransfer.DataFlavor; +import java.awt.datatransfer.UnsupportedFlavorException; +import java.awt.dnd.DnDConstants; +import java.awt.dnd.DropTargetAdapter; +import java.awt.dnd.DropTargetDropEvent; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.List; + +/** + * Project: Chess
+ * File: FENDropTarget.java
+ * Created: 13 Aug 2019
+ * Author: Kai S. K. Engelbart + */ +public class FENDropTarget extends DropTargetAdapter { + + private MainWindow mainWindow; + + public FENDropTarget(MainWindow mainWindow) { + this.mainWindow = mainWindow; + } + + @Override + public void drop(DropTargetDropEvent evt) { + try { + evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); + @SuppressWarnings("unchecked") + List droppedFiles = (List) evt.getTransferable() + .getTransferData(DataFlavor.javaFileListFlavor); + try (BufferedReader br = new BufferedReader(new FileReader(droppedFiles.get(0)))) { + mainWindow.getGame().reset(); + mainWindow.getGame().getBoard().initFromFEN(br.readLine()); + mainWindow.getBoardPane().getBoardComponent().repaint(); + mainWindow.getGame() + .getPlayers() + .get(mainWindow.getGame().getBoard().getLog().getActiveColor()) + .requestMove(); + evt.dropComplete(true); + } + } catch (UnsupportedFlavorException | IOException ex) { + ex.printStackTrace(); + evt.rejectDrop(); + } + } +} diff --git a/src/dev/kske/chess/ui/MainWindow.java b/src/dev/kske/chess/ui/MainWindow.java index fef681f..8a04b47 100644 --- a/src/dev/kske/chess/ui/MainWindow.java +++ b/src/dev/kske/chess/ui/MainWindow.java @@ -4,6 +4,7 @@ import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.Toolkit; +import java.awt.dnd.DropTarget; import javax.swing.JButton; import javax.swing.JFrame; @@ -93,6 +94,8 @@ public class MainWindow { mframe.setJMenuBar(new MenuBar(this)); + new DropTarget(mframe, new FENDropTarget(this)); + mframe.pack(); mframe.setLocationRelativeTo(null); }