我需要为这个我必须为Uni创建的程序提供一些帮助。问题是setColor和getColor方法不起作用,并且当我想要它时,该行也不会改变颜色。
如何将线条颜色更改为红色?
干杯
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);
}
}
答案 0 :(得分:3)
您需要在设置颜色后调用repaint()
public void setColor(Color colour) {
this.colour = colour;
colour = Color.RED;
// Repaint so the component uses the new color
repaint();
}
答案 1 :(得分:1)
或者,你可以摆脱setColor()方法。
然后你可以使用:
setForeground( colour );
控制要绘制的线条的颜色。
Graphics对象的颜色将设置为前景色,因此您也可以摆脱:
g.setColor( colour );