setBackground doesn't work on applet background

青春壹個敷衍的年華 提交于 2019-12-24 23:23:23

问题


I don't believe this is a duplicate because the other questions were in regards to JButtons and JPanels.

I was wondering why the following in java isn't working like one would assume:

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

public class Example extends JApplet
{
     public void paint(Graphics page)
     {
        setBackground (Color.cyan);
     }
}

Basically when I run the applet the background won't change, regardless of color. I realize there are other options to get the same effect, but I am using examples from a textbook and would like to know why it doesn't work on my machine.


回答1:


but I am using examples from a textbook

Get rid of the text book. You should never override the paint() method of JApplet (that is an old AWT technique and is not used with Swing).

Applets in Swing are just like applications in Swing. You add components to the content pane of the applet. Custom painting if you need to do it is done by overriding the paintComponent() method of a JPanel (or JComponent) and then you add the panel to the content pane.

If you want to change the background of the applet then you change the background of the content pane (or the background of the panel you add to the CENTER of the content pane). Something like:

getContentPane().setBackground( Color.CYAN );

This code would be executed in the init() method.

Start by reading the Swing tutorial. There are section on How to Make Applets and 'Performing Custom Painting`.



来源:https://stackoverflow.com/questions/8651915/setbackground-doesnt-work-on-applet-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!