setBackground在applet背景上不起作用 [英] setBackground doesn't work on applet background

查看:272
本文介绍了setBackground在applet背景上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不认为这是重复的,因为其他问题与JButtons和JPanels有关.

我想知道为什么Java中的以下内容无法像人们想象的那样起作用:

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

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

基本上,当我运行小程序时,无论颜色如何,背景都不会改变.我意识到还有其他选项可以达到相同的效果,但是我使用的是教科书中的示例,并且想知道为什么它在我的计算机上不起作用.

解决方案

但我使用的是教科书中的示例

摆脱课本.永远不要重写JApplet的paint()方法(这是一种旧的AWT技术,不与Swing一起使用).

Swing中的小程序就像Swing中的应用程序一样.您将组件添加到小程序的内容窗格.通过重写JPanel(或JComponent)的paintComponent()方法,然后将面板添加到内容窗格中,可以完成自定义绘制.

如果要更改小程序的背景,则可以更改内容窗格的背景(或添加到内容窗格的CENTER的面板的背景).像这样:

getContentPane().setBackground( Color.CYAN );

此代码将在init()方法中执行.

首先阅读 Swing教程.有关于How to Make Applets和执行自定义绘画"的部分.

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.

解决方案

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`.

这篇关于setBackground在applet背景上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆