anonymous
anonymous

Reputation: 508

White space at the right and bottom edge of the window

After I created a window, which should be completely black, there are white colors at the right and bottom edges. What is it that I may be doing wrong ?

this is the constructor where I do initialisation of window :-

    public Panel()
    {
        Thread t = new Thread(this);
        addKeyListener(this);
        setFocusable(true);
        this.setPreferredSize(new Dimension(gameWidth, gameHeight));
        JFrame f = new JFrame("AlienBusters");
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setResizable(false);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        t.start();
    }

this is the paint method where I made the window black :-

    @Override
    public void paintComponent(Graphics g)  
    {
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, gameWidth, gameHeight);
    }

Upvotes: 0

Views: 88

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347314

Five things...

  1. Calling setResizable after pack, not a good idea, setResizable can change the frame border size, which affects the available content size...
  2. Using KeyListener, seriously, see How to Use Key Bindings and save youreself the head ache...
  3. Relying on magic numbers instead of imperical values, g.fillRect(0, 0, gameWidth, gameHeight); should be g.fillRect(0, 0, getWidth(), getHeight()); or better, simply use setBackground(Color.BLACK) and get it for free via super.paintComponent...and paintComponent should be protected ;)
  4. Calling setPreferredSize. This means that the size could be changed, which, probably, isn't what you really want. Instead, override getPreferredSize instead. See Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? for more details
  5. Constructing a frame within the constructor of a component, the component shouldn't care how it's going to be displayed, it should just focus on it's job.

Upvotes: 2

Related Questions