Added drag and drop support for FEN files

This commit is contained in:
Kai S. K. Engelbart 2019-08-14 20:17:28 +02:00
parent c24613ba59
commit 79f55597c9
Signed by: kske
GPG Key ID: 8BEB13EC5DF7EF13
2 changed files with 53 additions and 0 deletions

View File

@ -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: <strong>Chess</strong><br>
* File: <strong>FENDropTarget.java</strong><br>
* Created: <strong>13 Aug 2019</strong><br>
* Author: <strong>Kai S. K. Engelbart</strong>
*/
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<File> droppedFiles = (List<File>) 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();
}
}
}

View File

@ -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);
}