简体   繁体   English

getContentPane()。setBackground()似乎不起作用

[英]getContentPane().setBackground() doesn't seem to work

I am trying to make a simple window appear with a red background, but it doesn't work. 我试图使一个带有红色背景的简单窗口出现,但是它不起作用。 For some reason I keep having a grey background, while my code is this: 由于某种原因,我的背景一直是灰色的,而我的代码是这样的:

import java.util.*;
import java.awt.*;
import javax.swing.*;

class Courses extends JFrame {

    private Image dbImage;
    private Graphics dbg;

    Courses(){
        setTitle("Course Schedule");
        setLayout(new FlowLayout());
        getContentPane().setBackground(Color.red);
        setSize(600,600);
        setLocation(300,10);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void paint(Graphics g){
        dbImage = createImage(getWidth(), getHeight());
        dbg = dbImage.getGraphics();
        paintComponent(dbg);
        g.drawImage(dbImage, 0, 0, this);
    }

    public void paintComponent(Graphics g){
        g.setColor(Color.white);
        g.fillOval(100,100,100,100);
        repaint();      
    }
}

public class canvas
{
    public static void main(String[] args){
        Courses C = new Courses();
    }
}

As you can see I extend the class with Jframe and use the method getContentPane().setBackground(), so this should draw a window with a red background (and a white oval), but instead I get a grey background (with a white oval). 如您所见,我使用Jframe扩展了该类并使用了getContentPane()。setBackground()方法,因此这应该绘制一个带有红色背景(和一个白色椭圆形)的窗口,但是却得到一个灰色背景(带有一个白色背景)椭圆)。 Can someone see what goes wrong? 有人可以看到出什么问题了吗?

Also I try to use buffer painting for the first time and I am not sure if that goes well right now, but that's not important. 我也尝试第一次使用缓冲区绘画,但我不确定现在是否进展顺利,但这并不重要。

In Java, calling repaint erases all drawn elements on screen (other than Swing Components). 在Java中,调用repaint会擦除屏幕上所有绘制的元素(Swing Components除外)。 This means that calling getContentPane().setBackground(Color.RED) is only visible until the frame is repainted (which you do right away). 这意味着调用getContentPane()。setBackground(Color.RED)仅在重新绘制框架之前可见(您立即执行此操作)。 To prevent this, it is good practice to call super.paint(g) at the start of the paint method, as this allows the JFrame to render visuals like background color before drawing. 为避免这种情况,优良作法是在paint方法的开始处调用super.paint(g) ,因为这允许JFrame在绘制之前呈现诸如背景色的视觉效果。

You could also consider using setColor(Color.RED) followed by clearRect(x, y, width, height) to change the background color. 您还可以考虑使用setColor(Color.RED)然后使用clearRect(x, y, width, height)更改背景颜色。 However, this is probably less efficient. 但是,这可能效率较低。

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

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