From previous experience, everyone will say "Don't use those setXxxSize
methods! Use a layout manager!" However, what should I do in this case?
import java.awt.*;
import javax.swing.*;
public class Game {
public static void main(String[] args) {
new Game();
}
public Game() {
JFrame f = new JFrame("Hi this is a game");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new GamePanel());
f.pack();
f.setVisible(true);
}
private class GamePanel extends JPanel {
private GamePanel() {
setPreferredSize(600, 600);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
//paint stuff
}
}
}
This is just some example code I threw together real quick. What should I do when I need to make the game area, say, 600 by 600? Is it okay to use setPreferredSize
here? I don't know of any layout manager that can just take a single component and give it a size, and even if there is, isn't it a lot easier to just use this instead of having to use an entire layout manager?
By the way, f.setSize(600, 600)
doesn't work here because it takes into account the frame decorations (title bar, border things).
So the question is if I only have one component that needs to be a specific size, what do I do?