From 86b696ef4c7e8fd5b5b1b0765f422f6ac2355c34 Mon Sep 17 00:00:00 2001 From: kske Date: Fri, 18 Oct 2019 17:45:13 +0200 Subject: [PATCH] Implemented game loading from FEN file --- src/dev/kske/chess/ui/MainWindow.java | 13 ++++++++++++- src/dev/kske/chess/ui/MenuBar.java | 21 ++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/dev/kske/chess/ui/MainWindow.java b/src/dev/kske/chess/ui/MainWindow.java index 68497c3..edaa113 100644 --- a/src/dev/kske/chess/ui/MainWindow.java +++ b/src/dev/kske/chess/ui/MainWindow.java @@ -70,12 +70,23 @@ public class MainWindow extends JFrame { /** * Creates a new {@link GamePane}, adds it to the tabbed pane and opens it. + * The new tab has the title {@code Game n} where {@code n} is its number. * * @return The new {@link GamePane} */ public GamePane addGamePane() { + return addGamePane("Game " + (tabbedPane.getComponentCount() + 1)); + } + + /** + * Creates a new {@link GamePane}, adds it to the tabbed pane and opens it. + * + * @param title The title of the {@link GamePane} + * @return The new {@link GamePane} + */ + public GamePane addGamePane(String title) { GamePane gamePane = new GamePane(); - tabbedPane.add("Game " + (tabbedPane.getComponentCount() + 1), gamePane); + tabbedPane.add(title, gamePane); tabbedPane.setSelectedIndex(tabbedPane.getComponentCount() - 1); return gamePane; } diff --git a/src/dev/kske/chess/ui/MenuBar.java b/src/dev/kske/chess/ui/MenuBar.java index 24a8bb5..588aa8c 100644 --- a/src/dev/kske/chess/ui/MenuBar.java +++ b/src/dev/kske/chess/ui/MenuBar.java @@ -2,6 +2,9 @@ package dev.kske.chess.ui; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import javax.swing.JMenu; import javax.swing.JMenuBar; @@ -47,7 +50,23 @@ public class MenuBar extends JMenuBar { final String extension = file.getName().substring(file.getName().lastIndexOf('.')).toLowerCase(); switch (extension) { case ".fen": - // TODO: Load board from FEN + try { + final GamePane gamePane = mainWindow + .addGamePane(file.getName().substring(0, file.getName().lastIndexOf('.'))); + final String fen = new String(Files.readAllBytes(file.toPath()), + StandardCharsets.UTF_8); + DialogUtil.showGameConfigurationDialog((whiteName, blackName) -> { + final Game game = new Game(gamePane.getBoardPane(), whiteName, blackName, fen); + gamePane.setGame(game); + game.start(); + }); + } catch (IOException e) { + e.printStackTrace(); + JOptionPane.showMessageDialog(mainWindow, + "Failed to load the file " + file.getName() + ": " + e.toString(), + "File loading error", + JOptionPane.ERROR_MESSAGE); + } break; case ".pgn": // TODO: Load board from PGN