From 198267c3b14ec74b2d1d4d66e30cde1345464370 Mon Sep 17 00:00:00 2001 From: CyB3RC0nN0R Date: Tue, 5 Nov 2019 05:51:41 +0100 Subject: [PATCH] Using reflection in FENString, fixed input field in MainWindow --- src/dev/kske/chess/board/FENString.java | 28 ++++++++----------------- src/dev/kske/chess/ui/MainWindow.java | 2 +- 2 files changed, 10 insertions(+), 20 deletions(-) diff --git a/src/dev/kske/chess/board/FENString.java b/src/dev/kske/chess/board/FENString.java index 8f27140..28c890a 100644 --- a/src/dev/kske/chess/board/FENString.java +++ b/src/dev/kske/chess/board/FENString.java @@ -1,5 +1,7 @@ package dev.kske.chess.board; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -80,25 +82,13 @@ public class FENString { j += Character.getNumericValue(c); } else { Color color = Character.isUpperCase(c) ? Color.WHITE : Color.BLACK; - switch (Character.toUpperCase(c)) { - case 'K': - board.getBoardArr()[j][i] = new King(color, board); - break; - case 'Q': - board.getBoardArr()[j][i] = new Queen(color, board); - break; - case 'R': - board.getBoardArr()[j][i] = new Rook(color, board); - break; - case 'N': - board.getBoardArr()[j][i] = new Knight(color, board); - break; - case 'B': - board.getBoardArr()[j][i] = new Bishop(color, board); - break; - case 'P': - board.getBoardArr()[j][i] = new Pawn(color, board); - break; + try { + Constructor pieceConstructor = Piece.fromFirstChar(c).getDeclaredConstructor(Color.class, Board.class); + pieceConstructor.setAccessible(true); + board.getBoardArr()[j][i] = pieceConstructor.newInstance(color, board); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException + | NoSuchMethodException | SecurityException e) { + e.printStackTrace(); } ++j; } diff --git a/src/dev/kske/chess/ui/MainWindow.java b/src/dev/kske/chess/ui/MainWindow.java index efa318c..b4c8b5e 100644 --- a/src/dev/kske/chess/ui/MainWindow.java +++ b/src/dev/kske/chess/ui/MainWindow.java @@ -147,7 +147,7 @@ public class MainWindow extends JFrame { gameNames[i] = String.format("%s vs %s: %s", game.getTag("White"), game.getTag("Black"), game.getTag("Result")); } JComboBox comboBox = new JComboBox<>(gameNames); - JOptionPane.showInputDialog(this, comboBox, "Select a game", JOptionPane.QUESTION_MESSAGE); + JOptionPane.showMessageDialog(this, comboBox, "Select a game", JOptionPane.QUESTION_MESSAGE); board = pgnDB.getGames().get(comboBox.getSelectedIndex()).getBoard(); } else throw new ChessException("The PGN database '" + name + "' is empty!"); break;