javafxgraphicscontext

Why doesnt my piece of code accept a color as parameter?


So I am trying to create something that draws axis on a canvas. I want to set the color of the axis to red by using the setStroke method but it tells me that I am giving a wrong type parameter. The thing that puzzles me is that ,whilst using someones example code it doesnt give an error at all. My code :

package lissa;

import java.awt.Color;
import javafx.scene.Node;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;

public class kalf extends Canvas{
    private GraphicsContext gc ;
    private Color kleurAs;

    public kalf(Node achtergrond){
        super(); // hoe moet je de grootte instellen?
        gc = getGraphicsContext2D();
        kleurAs = Color.RED;
        tekenAs(gc);
    }

    public void tekenAs(GraphicsContext gc){

//here is the problem

    gc.setStroke(kleurAs);          
    gc.strokeLine(d, d1, d2, d3); 
}

Example code:

public class LissajousCanvas extends Canvas {

private final LissajousData data;
private static final int AANT_PTN = 200;
private static final int RAND = 5;
private final GraphicsContext gc;
private final int factor;
private Color kleurAs;
private ContextMenu menu;

public LissajousCanvas(LissajousData data, double width, double height) {
    super(width, height);
    this.data = data;
    gc = this.getGraphicsContext2D();
    factor = Math.min((int) getWidth(), (int) getHeight()) - 2 * RAND;
    kleurAs = Color.RED;
    tekenAssen();
    getStyleClass().add("canvas");
    maakContextMenu();
    final LissajousCanvas canvas = this;
    addEventHandler(MouseEvent.MOUSE_CLICKED,
            new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent e) {
                    if (e.getButton() == MouseButton.SECONDARY) {
                        menu.show(canvas, e.getScreenX(), e.getScreenY());
                    }
                }
            });
}

private void tekenAssen() {

//this is where it is correctly employed ,whilst still using GraphicsContext as caller + having a

//color for parameter

     gc.setStroke(kleurAs);

     gc.strokeLine(0, factor / 2 + RAND, factor + 2 * RAND, factor / 2 + RAND);
     gc.strokeLine(factor / 2 + RAND, 0, factor / 2 + RAND, factor + 2 * RAND);

}
}

Any ideas why the first piece of code is incorrect and the second one isnt?


Solution

  • You use the wrong import. JavaFX has it's own Color class.

    Use

    import javafx.scene.paint.Color;
    

    instead of

    import java.awt.Color;