有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

尝试使用渐变绘制时,java setPaint()不起作用

我对Java非常陌生,正在使用图形用户界面绘制形状。这是我们班画圆的一个例子。我需要添加的能力,它绘制的形状与颜色梯度。调用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();

    }

}

共 (1) 个答案

  1. # 1 楼答案

    ^{}方法是Graphics2D类的一部分,而不是Graphics类的一部分。传递给Swing组件的绘制方法的图形实例通常是Graphics2D对象。也就是说,它可以被强制转换为Graphics2D实例