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 8e2af63c35
commit 358654b1ed
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.EventQueue;
import java.awt.GridLayout; import java.awt.GridLayout;
import java.awt.Toolkit; import java.awt.Toolkit;
import java.awt.dnd.DropTarget;
import javax.swing.JButton; import javax.swing.JButton;
import javax.swing.JFrame; import javax.swing.JFrame;
@ -93,6 +94,8 @@ public class MainWindow {
mframe.setJMenuBar(new MenuBar(this)); mframe.setJMenuBar(new MenuBar(this));
new DropTarget(mframe, new FENDropTarget(this));
mframe.pack(); mframe.pack();
mframe.setLocationRelativeTo(null); mframe.setLocationRelativeTo(null);
} }