1

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?

tckmn
  • 57,719
  • 27
  • 114
  • 156

2 Answers2

4

Override getPreferredSize, in GamePanel:

public Dimension getPreferredSize(){
    return new Dimension(600, 600);
}
Mordechai
  • 15,437
  • 2
  • 41
  • 82
1

Why do this and not just setPreferredSize()?

As Game is a JPanel that is

  • Used solely for drawing,

  • Contains a default layout but no components and

  • Has a standard UI delegate,

the difference is negligible. There are still reasons to override getPreferredSize()

  • The intent is clear to other developers; demos and prototypes, like zombies, never go away.

  • Any one or all of those conditions may change as the class evolves.

  • It's an idiomatic reminder not to fall into this trap.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045