0

I am having an issue. My JFrame starts with contents inside of it, but displays transparently with the contents on top.

package javagame;

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;

public class JavaGame extends JFrame{

    public JavaGame(){
        setTitle("Java Game");
        setSize(500, 500);
        setResizable(false);
        setVisible(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void paint (Graphics g){
        g.drawString("Hello World!", 250, 250);
    }

    public static void main(String[] args){

        new JavaGame();

    }

}

Help is appreciated! (:

mKorbel
  • 109,525
  • 20
  • 134
  • 319
KanViInte
  • 3
  • 1

1 Answers1

2

Two things...

First...

You are breaking the paint chain...

public void paint (Graphics g){
    // You MUST call super.paint here...
    g.drawString("Hello World!", 250, 250);
}

Second

You should avoid, at all cost, overriding paint of a top level container like JFrame. Lots of reasons, one of which you just found, but also because top level containers are not double buffered, which will introduce flickering when the are painted and JFrame contains a bunch of other components, the JRootPane, the content pane, the glass pane...all of which could paint over what you are trying to paint.

Also, painting directly to the frame allows you to paint under the frame's decorations, which isn't really what you want to do...

For example (of why it's bad)...

The solution...

Create a custom class extending from something like JPanel and override it's paintComponent method and perform your custom painting there. You gain double buffering support for free and no longer have to worry about the frame's borders, as the content pane will ensure that it's maintained with inside the frame decorations.

See Painting in AWT and Swing and Performing Custom Painting for more details

Also, call setResizable before setting the size of the frame, this changes the size of the frames decorations and can produce unexpected additional spacing within the frames content area...

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366