简体   繁体   English

如何更改小程序的颜色

[英]How To Change Applet Color

I need some help with this program I have to create for Uni. 我需要为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. 问题是setColor和getColor方法不起作用,并且当我也想要它时,行也不会更改颜色。

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 setControlPoint(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 设置颜色后,您需要调用repaint()

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. 或者,您可以摆脱setColor()方法。

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: Graphics对象的颜色将被设置为前景色,因此您也可以摆脱:

g.setColor( colour );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM