简体   繁体   中英

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.

框架表现不佳

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();
    }

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

I used something like this:

public class gui {
public static void main(String args[]) {
    JFrame tobi = new JFrame("youwillneverfigurethisout");
    tobi.setVisible(true);
    tobi.setTitle("Xbatz GUI Example");
    tobi.setSize(400, 200);
    tobi.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
}

And it works perfectly. Maybe try to change the order of things to what i have

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM