Java Applet:setForeground() 究竟是做什么的?以及如何看到它的效果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34262447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:39:58  来源:igfitidea点击:

Java Applet: setForeground() what exactly it does? and how to see it's effect?

javaapplet

提问by Majid NK

As per "Java - The Complete Reference Java" setForeground()is used to set the foreground colour i.e the colour in which text is shown.

根据“Java - The Complete Reference Java”setForeground()用于设置前景色,即显示文本的颜色。

Now consider this basic applet program that sets the foreground and background colours and outputs a string:

现在考虑这个设置前景色和背景色并输出一个字符串的基本小程序程序:

import java.awt.*;
import java.applet.*;

/*
< applet code="Sample" width=1000 height=500>
< /applet>
*/

public class Sample extends Applet
{
    String msg;
    // set the foreground and background colors.

    public void init() 
    {
        setBackground(Color.white);
        setForeground(Color.red);
        msg = "Inside init( ) --";
    }

    // Initialize the string to be displayed.
    public void start()
    {
        msg += " Inside start( ) --";
    }

    // Display msg in applet window.
    public void paint(Graphics g)
    {
      msg += " Inside paint( ).";
      g.drawString(msg, 10, 30);
    }
}

The background colour can be changed to any colour by setBackground()BUT no matter what colour given inside setForegorund() the text is always black!!!i.e it does not change the text colour at all. Then what is the function/use of setForegorund(), and how can I see the effect of it?

The background colour can be changed to any colour by setBackground()但是无论在 setForegorund() 中给出什么颜色,文本总是黑色!!!即它根本不改变文本颜色。那么它的作用/用途是什么setForegorund(),怎么看效果呢?

Thank you

谢谢

采纳答案by RealSkeptic

Basically, it has no effect unless your code makes use of the method getForeground().

基本上,除非您的代码使用方法,否则它没有任何效果getForeground()

Swing, built on top of AWT, makes use of it when it calls getComponentGraphics()- a protected method of JComponentit uses in its paint()method where it paints component borders etc. But AWT itself doesn't have any internal use for the foreground color, and doesn't use it by default for painting.

Swing 构建在 AWT 之上,在调用时使用它getComponentGraphics()——它的一个受保护的方法JComponent在它的paint()方法中使用它绘制组件边框等。但是 AWT 本身没有任何内部使用前景色,并且没有默认情况下将其用于绘画。

You can use it by using graphics.setColor(getForeground())if you wish.

您可以根据需要使用它graphics.setColor(getForeground())