Java 2D: Why won't my JPanel let me resize it?
-
11-11-2019 - |
题
Ok so I am trying to add a JPanel to a JFrame as so:
gameClasses[2] = new a2();
gameClasses[2].setSize(100, 100);
menu.add(gameClasses[2]);
menu.setVisible(true);
a2() is a separate class that acts as a JPanel which I use the paintComponent to paint images to it. "menu" is the JFrame. My problem is when I call "gameClasses[2].setSize(100, 100);" it does not resize the JPanel but it stays the same size. Does anyone know what I am doing wrong or how this is supposed to be done because no one else seems to have any issues with this on the internet. Thanks.
EDIT: Here is the code related to menu and a2:
menu.setSize(swidth / 2 + swidth / 5, sheight / 2 + sheight / 5);
menu.setLocation((swidth - menu.getWidth()) / 2, (sheight - menu.getHeight()) / 3);
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.setResizable(true);
menu.remove(main);
menu.add(gameClasses[0] = new a3());
menu.add(gameClasses[1] = new a4());
gameClasses[2] = new a2();
gameClasses[2].setSize(100, 100);
gameClasses[2].validate();
menu.add(gameClasses[2]);
menu.setVisible(true);
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class a2 extends JPanel {
public static int size = 48;
public static Image grsX = Toolkit.getDefaultToolkit().getImage("tiles/grsX.png");
public static Image grsY = Toolkit.getDefaultToolkit().getImage("tiles/grsY.png");
public static Image grsX1 = Toolkit.getDefaultToolkit().getImage("tiles/grsX1.png");
public static Image grsY1 = Toolkit.getDefaultToolkit().getImage("tiles/grsY1.png");
public a2() {
System.out.println("a2 loaded...");
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
//draw interface
for(int y = 0; y < a6.ay; y++) {
for(int x = 0; x < a6.ax; x++) {
g.drawImage(a5.Tile_Img.get(a5.ID_Tile.get(a6.area[x][y])), x * size, y * size, size, size, this);
if(x > 0) {
if(a6.area[x - 1][y].equals("00") && a6.area[x][y].equals("01")) {
g.drawImage(grsX, x * size, y * size, size, size, this);
}
}
if(x < a6.ax - 1) {
if(a6.area[x + 1][y].equals("00") && a6.area[x][y].equals("01")) {
g.drawImage(grsX1, x * size, y * size, size, size, this);
}
}
if(y > 0) {
if(a6.area[x][y - 1].equals("00") && a6.area[x][y].equals("01")) {
g.drawImage(grsY, x * size, y * size, size, size, this);
}
}
if(y < a6.ay - 1) {
if(a6.area[x][y + 1].equals("00") && a6.area[x][y].equals("01")) {
g.drawImage(grsY1, x * size, y * size, size, size, this);
}
}
}
}
repaint();
}
}
a3 and a4 are a KeyListener class and a MouseListener class that both extend JPanel
没有正确的解决方案
不隶属于 StackOverflow