WITSorcery
WITSorcery

Reputation: 9

Java JFrame is displayed incorrectly

When I run my program, the JFrame shows what is in the JFrame and then what is behind the JFrame when it is opened.

frame behaving badly

public class ChuckysAdventure extends JFrame { // Main Class

    public ChuckysAdventure(){
        setTitle("Chuckys Adventure");
        setSize(700, 700);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void paint (Graphics g){
        g.drawString("Hi. I'm Chucky. Wanna play?", 250, 250);
    }
    public static void main(String[] args){  // Starts game
         new ChuckysAdventure();
    }

Upvotes: 0

Views: 131

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

Welcome to the wonderful world of "Honey, I broke the paint chain"...

Painting in Swing is made up of a series of chained method calls which work together to produce the final result, one of those methods actually fills the Graphics context with the components background color

Failing to honour this paint chain will cause no end of paint artifacts. Graphics is a shared resource, meaning that everything that is painted within a given paint cycle will use the same instance of the Graphics context. If you fail to ensure that the paint chain is completed properly, you will end up with any number of awesome paint artifacts.

Your initial fix would be to change...

public void paint (Graphics g){
    g.drawString("Hi. I'm Chucky. Wanna play?", 250, 250);
}

to...

public void paint (Graphics g){
    super.paint(g);
    g.drawString("Hi. I'm Chucky. Wanna play?", 250, 250);
}

You next fix would be to avoid overriding paint of top level containers like JFrame a part from the fact that it's not double buffered and painting will occur beneath the frames decorations, its all to easy to completely screw up the paint process

Instead, you should be using something like JPanel and overriding it's paintComponent method instead

Take a look at Performing Custom Painting and Painting in AWT and Swing for more details

Upvotes: 9

Related Questions