xArd
xArd

Reputation: 49

Color param in Applet

I want to pass a color from parameters to change the color of the the text but when I put the param element in the HTML no color at all is being displayed. I am using Netbeans 7.1.

Why is the color not being displayed?

HTML

<HTML>
<HEAD>
   <TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>
 <H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3>
<P>
  <APPLET codebase="classes" code="ex1/ex11.class" width=350 height=200>
   <PARAM name="color" value="black"/>
    </APPLET>
 </P>
<HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>
</BODY>
</HTML>

Code

package ex1;

import java.awt.*;
import javax.swing.JApplet;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

public class ex11 extends JApplet implements ActionListener{
    int i ;
    String color;

    @Override
    public void init() 
    {
        Timer timer = new Timer(600, this);
        timer.start();
        i=0;
        this.setSize(900,900);   
    }

    @Override
    public void paint(Graphics g) 
    {
        g.clearRect(0, 0, this.getWidth(), this.getHeight());
        g.setFont(new Font(Font.MONOSPACED, Font.BOLD, 40));
        g.setColor(Color.getColor(getParameter("color")));
        g.drawString(""+i, 250, 150);
    }

    public void actionPerformed(ActionEvent e)
    {
        if (i <5)
        {
            i= i+1;
            repaint();
        }
    }
}

Upvotes: 1

Views: 2462

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168845

As discussed by @Emmanuel Bourg, Color.getColor(String) does not work the way you want to use it. See Color.decode(String) instead.

g.setColor(Color.decode("#ff0000"));  // Very RED

Upvotes: 1

Emmanuel Bourg
Emmanuel Bourg

Reputation: 11078

Color.getColor() gets a color from the system properties, not from the applet parameters. Also this method doesn't work with color names like black, you have to use a numeric value.

If you want to read the colors from the applet parameters you can use Apache Commons Configuration like this:

DataConfiguration config = new DataConfiguration(new AppletConfiguration(applet));
Color color = config.getColor("color");

If you don't want to introduce a dependency you can parse the color like this (for hexadecimal numeric values only):

public Color getColor(String key) {
    int i = Integer.parseInt(getParameter(key));
    return new Color((i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);
}

Upvotes: 1

Related Questions