我是Java的新手,并且正在开发绘制形状的GUI。这是我的绘制圆圈类的一个例子。我需要添加它用颜色渐变绘制形状的能力。看起来调用setPaint()的唯一方法是在paint方法中。它不会识别我的drawShape(Graphics g)方法中的方法。有办法解决这个问题吗?我希望能够在课堂上打电话。
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.io.Serializable;
public class Oval extends Shape implements Serializable {
//Default constructor
public Oval() {
}
//Constructor
public Oval(int c1, int c2, int c3, int c4, int c5, int c6, int c7, boolean d, boolean f, int tran, int s, String ss, boolean g, Color ccc1, Color ccc2) {
component1 = c1;
component2 = c2;
component3 = c3;
component4 = c4;
red = c5;
green = c6;
blue = c7;
dashed = d;
thick = false;
fill = f;
trans = tran;
stroke = s;
textBox = ss;
gFlag = g;
cc1 = ccc1;
cc2 = ccc2;
}
@Override
public void drawShape(Graphics g) {
g.setColor(new Color(red, green, blue, trans));
if (gFlag == true) {
Graphics g2d = (Graphics2D) g;
GradientPaint gp2 = new GradientPaint(0, 0, cc1, 10, 10, cc2);
//Error
g2d.setPaint(gp2);
} else if (dashed == true && fill != true) {
Graphics2D g2d = (Graphics2D) g;
float[] fa = {10, 10, 10};
BasicStroke bs = new BasicStroke(stroke, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10, fa, 10);
g2d.setStroke(bs);
g2d.drawOval(component1, component2, component3, component4);
} else if (dashed != true && fill != true) {
Graphics2D g2d = (Graphics2D) g;
BasicStroke bs = new BasicStroke(stroke);
g2d.setStroke(bs);
g2d.drawOval(component1, component2, component3, component4);
} else if (fill == true) {
g.fillOval(component1, component2, component3, component4);
System.out.println("FILLED OVAL DRAWN");
}
System.out.println("Oval Drawn.");
}
Shape copy() {
return new Oval();
}
}
答案 0 :(得分:1)
Graphics2D.setPaint(Paint)
方法是Graphics2D
类的一部分,不是类Graphics
类。传递给Swing组件的paint方法的绘图实例通常是Graphics2D
对象。 I.E.它可以转换为Graphics2D
实例。