简体   繁体   English

setBackground在applet背景上不起作用

[英]setBackground doesn't work on applet background

I don't believe this is a duplicate because the other questions were in regards to JButtons and JPanels. 我不认为这是重复的,因为其他问题与JButtons和JPanels有关。

I was wondering why the following in java isn't working like one would assume: 我想知道为什么Java中的以下内容无法像人们想象的那样工作:

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. 我意识到还有其他选项可以达到相同的效果,但是我使用的是教科书中的示例,并且想知道为什么它在我的计算机上不起作用。

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). 永远不要重写JApplet的paint()方法(这是一种古老的AWT技术,不与Swing一起使用)。

Applets in Swing are just like applications in Swing. Swing中的Applet就像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. 通过重写JPanel(或JComponent)的paintComponent()方法,然后将面板添加到内容窗格中,可以完成自定义绘制(如果需要)。

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). 如果要更改小程序的背景,则可以更改内容窗格的背景(或添加到内容窗格的CENTER的面板的背景)。 Something like: 就像是:

getContentPane().setBackground( Color.CYAN );

This code would be executed in the init() method. 该代码将在init()方法中执行。

Start by reading the Swing tutorial . 首先阅读Swing教程 There are section on How to Make Applets and 'Performing Custom Painting`. 有关于How to Make Applets和“执行自定义绘画”的部分。

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

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