简体   繁体   English

Java JFrame显示不正确

[英]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. 当我运行程序时, JFrame显示JFrame ,然后显示JFrame打开后的内容。

框架表现不佳

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 Swing中的绘画由一系列链接在一​​起的方法调用组成,这些方法调用一起工作以产生最终结果,其中一个方法实际上用组件的背景色填充了Graphics上下文。

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. Graphics是共享资源,这意味着在给定绘制周期内绘制的所有内容都将使用Graphics上下文的相同实例。 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 你未来的解决将是避免压倒一切的paint顶层容器一样的JFrame从事实的一部分,它不是双缓冲和绘画将发生帧装饰下,它的所有容易完全搞砸了烤漆工艺

Instead, you should be using something like JPanel and overriding it's paintComponent method instead 相反,您应该使用JPanel之类的东西,并改写它的paintComponent方法

Take a look at Performing Custom Painting and Painting in AWT and Swing for more details 看一下在AWT和Swing执行自定义绘画绘画以获取更多详细信息

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 也许尝试将事物的顺序更改为我所拥有的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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