开发者

How To Change Applet Color

I need some help with this program I have to create for Uni. The problem is that the setColor and getColor methods do no work, and the line doesn't change color when I want it too.

What do I need to do to change the color of the line to red?

Cheers

import java.awt.Color;
import java.awt.Point;
import javax.swing.JPanel;
import java.awt.*;

public class Shape extends JPanel {
static Point startPoint = new Point(0, 0);
Point controlPoint = new Point(0, 0);

Color colour = Color.BLACK;

public Shape() {
    this(startPoint);

}

public Shape(Point startPoint) {
    // initialise variable startPoint
    this.startPoint = startPoint;
    // execute methods setColour and setControlPoint
    setColor(colour);
    setControlPoint(controlPoint);
    // change startPoint
    startPoint.x = 50;
    startPoint.y = 50;

}

public void setColor(Color colour) {
    this.colour = colour;
    colour = Color.RED;
}

public Color getColor() {
    return colour;
}

public void setCont开发者_开发问答rolPoint(Point controlPoint) {
    controlPoint.x = 150;
    controlPoint.y = 150;
}

public void paintComponent(Graphics g) {
    super.paintComponents(g);
    g.setColor(colour);
    g.drawLine(startPoint.x, startPoint.y, controlPoint.x, controlPoint.y);
}

}


You need to call repaint() after the color is set

public void setColor(Color colour) {
    this.colour = colour;
    colour = Color.RED;

    // Repaint so the component uses the new color
    repaint();
}


Or, you can get rid of the setColor() method.

Then you can use:

setForeground( colour );

to control the color of the line to be drawn.

The color of the Graphics object will be set to the foreground colour so you can also get rid of:

g.setColor( colour );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜