0

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);
    }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
anonymous
  • 448
  • 1
  • 6
  • 25
  • 1
    Don't call your class "Panel". There is an AWT component with that class name and it is confusing. Your class name should be more descriptive. – camickr Dec 11 '14 at 06:10

1 Answers1

2

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.
Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366