Fixed board size issues

- TextureLoader does not perform scaling anymore
+ Scaling method in BoardPanel
This commit is contained in:
Kai S. K. Engelbart 2019-07-02 22:06:48 +02:00
parent f15898d29e
commit 6abd2bfca8
3 changed files with 20 additions and 21 deletions

View File

@ -1,7 +1,6 @@
package dev.kske.chess;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
@ -38,6 +37,10 @@ public class BoardPanel extends JPanel {
private Board board;
static {
loadPieceTextures();
}
public BoardPanel(Board board) {
this();
setSize(getPreferredSize());
@ -55,9 +58,7 @@ public class BoardPanel extends JPanel {
@Override
public void componentResized(ComponentEvent e) {
tileSize = getWidth() / 8;
// Load the piece textures if they are not present
if (textures == null) loadPieceTextures();
scalePieceTextures();
}
});
@ -110,6 +111,13 @@ public class BoardPanel extends JPanel {
textures.put(file.getName().replaceFirst("[.][^.]+$", ""), TextureLoader.loadScaledImage(file, tileSize));
}
/**
* Scales all piece textures to fit the current tile size
*/
private static void scalePieceTextures() {
textures.replaceAll((key, img) -> img.getScaledInstance(tileSize, tileSize, Image.SCALE_SMOOTH));
}
/**
* Loads a piece texture fitting to a piece object
*
@ -128,16 +136,7 @@ public class BoardPanel extends JPanel {
public Dimension getMaximumSize() { return getPreferredSize(); }
@Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
Container c = getParent();
if (c != null) d = c.getSize();
else return new Dimension(480, 480);
int w = (int) d.getWidth();
int h = (int) d.getHeight();
int s = Math.max(w, h);
return new Dimension(s, s);
}
public Dimension getPreferredSize() { return new Dimension(480, 480); }
public Board getBoard() { return board; }

View File

@ -45,12 +45,14 @@ public class Chess {
*/
private void initialize() {
mframe = new JFrame();
mframe.setBounds(100, 100, 740, 740);
mframe.setResizable(false);
mframe.setBounds(100, 100, 729, 737);
mframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BoardPanel boardPanel = new BoardPanel(new Board());
boardPanel.setLayout(null);
mframe.getContentPane().add(boardPanel, BorderLayout.CENTER);
mframe.pack();
}
}

View File

@ -18,11 +18,10 @@ public class TextureLoader {
private TextureLoader() {}
/**
* Loads an image from a file and scales it to a square.
* Loads an image from a file.
*
* @param file The image file
* @param scale The side length of the square to which the image will be scaled
* @return The scaled image
* @return The loaded image
*/
public static Image loadScaledImage(File file, int scale) {
BufferedImage in = null;
@ -31,7 +30,6 @@ public class TextureLoader {
} catch (IOException e) {
e.printStackTrace();
}
Image scaled = in.getScaledInstance(scale, scale, Image.SCALE_SMOOTH);
return scaled;
return in;
}
}