I want to create a Custom size JPanel for my map and later mini-map, the map generator and spritesheet reader work fine however when I set the JPanel to a different size then the JFrame and I use the setSize() or setBounds() and run the program, it stays the same dimensions as the JFrame.
Main class:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main extends JPanel {
private static SpriteSheet sc = new SpriteSheet();
private static JLabel[][] mapTiles = new JLabel[40][40];
private static int[][] mapTileCode = new int[40][40];
public Main() {
JFrame f = new JFrame();
setLayout(null);
this.setSize(625, 625);
f.add(this);
f.setSize(1000, 1000);
f.setUndecorated(true);
f.setLocationRelativeTo(null);
this.setBackground(new Color(150, 150, 150));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public static void main(String args[]) {
new Main().mapSetup();
}
public void mapSetup() {
Random r = new Random();
for (int x = 0; x < 40; x++) {
for (int y = 0; y < 40; y++) {
int l = r.nextInt(6);
BufferedImage i = sc.getTile(l);
ImageIcon im = new ImageIcon(i);
mapTileCode[y][x]=l;
mapTiles[y][x] = new JLabel(im);
mapTiles[y][x].setBounds(y * 25, x * 25, 25, 25);
this.add(mapTiles[y][x]);
repaint();
}
}
}
}
SpriteSheet class:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class SpriteSheet {
final int W = 25;
final int H = 25;
BufferedImage spriteSheet;
public BufferedImage getTile(int tile) {
if (new File("img/SpriteSheet.png").exists()) {
try {
spriteSheet = ImageIO.read(new File("img/SpriteSheet.png"));
} catch (IOException e) {
e.printStackTrace();
}
int tileX = 1 + tile + (tile * 25);
int tileY = 1 + (0 * 25);
return spriteSheet.getSubimage(tileX, tileY, 25, 25);
} else {
System.err.println("no files found");
return null;
}
}
}
The results you are seeing are a result of the LayoutManager. You have (at least) two options:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.