WiredDrummer
WiredDrummer

Reputation: 23

JavaFX Canvas and BorderPane

I'm currently working on a project in JavaFX and I'm doing the GUI with BorderPane. I have successfully created a menu and accordion, and added them to the positions I wanted (top and right).

Now I've created a class that extends Canvas and want to add it to the left side, but it doesn't seem to be working.

What I need is the app to have a menu, extendable options on the right (accordion) and space to draw images on the remaining space (left).

Can anyone shed some light?

Adding some code!

public class PainelCanvas extends Canvas implements DesenhoCanvas {

    //ATRIBUTOS
    Canvas canvas;

    //CONSTRUTOR
    public PainelCanvas() {
        canvas = new Canvas(400, 400);
        GraphicsContext gc = canvas.getGraphicsContext2D();
        desenhar(gc);
    }

    @Override
    public void desenhar(GraphicsContext gc) {
        gc.setFill(Color.GREEN);
        gc.fillText("adsads", 20, 30);
    }

}

In my main class, I'm creating an object of PainelCanvas and adding it to my BorderPane.

BorderPane root = new BorderPane();
PainelMenu menu = new PainelMenu();
PainelCanvas canvas = new PainelCanvas();
PainelAccordion painel = new PainelAccordion();

//Definir localização dos vários elementos gráficos
root.setTop(menu);  
root.setLeft(canvas);
root.setRight(painel);

Upvotes: 0

Views: 1359

Answers (1)

James_D
James_D

Reputation: 209684

Your canvas has no width or height set, and no content.

Note that you do

public class PainelCanvas extends Canvas ...

and

PainelCanvas canvas = new PainelCanvas();
// ...
root.setLeft(canvas);

So PainelCanvas is a Canvas and is the Canvas you add to your BorderPane.

Inside the PainelCanvas you create another Canvas:

canvas = new Canvas(400, 400);

and add some content to it:

GraphicsContext gc = canvas.getGraphicsContext2D();
// ...
gc.fillText(...);

But that canvas is never added to the BorderPane.

If you really want to extend Canvas (not really recommended) you should do

public class PainelCanvas extends Canvas implements DesenhoCanvas {
    public PainelCanvas() {
        super(400, 400);
        GraphicsContext gc = this.getGraphicsContext2D();
        desenhar(gc);
    }
    // desenhar(...) method as before
}

But I prefer not to subclass Node classes unless really necessary ("favor aggregation over inheritance").

Recommended solution:

public class PainelCanvas implements DesenhoCanvas {
    private Canvas canvas ;
    public PainelCanvas() {
        canvas = new Canvas(400, 400);
        GraphicsContext gc = canvas.getGraphicsContext2D();
        desenhar(gc);
    }

    // desenhar(...) as before...

    public Node getView() {
        return canvas ;
    }
}

and then:

root.setLeft(canvas.getView());

Upvotes: 1

Related Questions