Java Applet:setForeground()它到底是做什么的?如何查看它的效果?

3
根据《Java - The Complete Reference Java》所述,setForeground()用于设置前景色,即文本显示的颜色。
现在考虑以下基本小程序,它设置前景色和背景色,并输出一个字符串:
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);
    }
}

setBackground()函数可以将背景色更改为任何颜色。

但是,无论在setForegorund()中设置什么颜色,文本始终是黑色!!!

也就是说,它根本没有改变文本颜色。那么setForegorund()的功能/用途是什么?我该如何看到它的效果呢?

谢谢


是的,正如我已经提到的,setBackground() 可以使用任何颜色。 - Majid NK
由于您正在覆盖paint()方法,请考虑在该方法中设置颜色:g.setColor(Color.RED); - Arnaud
对不起,我的意思是 setForeground()。是的,g.setColor(Color.red); 可以工作,但我的问题是 setForeground() 的效果。谢谢。 - Majid NK
1
setForeground 方法被用于调用组件上的 Panel、TextField、Button 等等。它旨在设置 Component 的默认 paint 方法所使用的前景色。只要你重写了 paint 方法,我相信你就不能信任这个调用,你需要负责设置所有 Graphics 对象的参数。不过,在你的 paint 方法开始时尝试调用 super.paint,因为它应该首先调用你小程序的默认 paint 方法,并且可能会将 Graphics 对象的颜色设置为前景色。 - Arnaud
谢谢您的建议,但是它会出现错误:错误:paint()没有找到合适的方法 super.paint(); - Majid NK
显示剩余3条评论
1个回答

2

基本上,除非你的代码使用了方法getForeground(),否则它没有任何影响。

Swing是建在AWT之上的,在调用getComponentGraphics()时使用它- 这是JComponent的受保护方法,用于paint()方法中绘制组件边框等。 但是,AWT本身没有对前景色的内部使用,并且默认情况下不使用它进行绘图。

如果需要,您可以使用graphics.setColor(getForeground())来使用。


非常感谢,它起作用了。正如你所说,在paint()中使用setColor(getForeground())利用setForeground(Color.x)并将文本颜色更改为在init()中定义的x :) - Majid NK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接