Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JavaFX 8 - Reasonable way to make a canvas fill its parent

2995851Jul 21 2015 — edited Jul 21 2015

This here is the essence of a problem with a canvas i have right now

public class Test extends Application

{

public static void main(String[] args)

{

launch(args);

}

@Override

public void start(Stage primaryStage)

{

TabPane tabPane = new TabPane();

Tab tab = new Tab("Tab");

tabPane.getTabs().add(tab);

BorderPane borderPane = new BorderPane();

tab.setContent(borderPane);

MyCanvas canvas = new MyCanvas();

borderPane.setCenter(canvas);

canvas.setWidth(500);

canvas.heightProperty().bind(borderPane.heightProperty());

Scene scene = new Scene(tabPane, 1300, 800);

primaryStage.setScene(scene);

primaryStage.show();

}

class MyCanvas extends Canvas

{

public MyCanvas()

{

  this.widthProperty().addListener(evt -> draw());

  this.heightProperty().addListener(evt -> draw());

}

private void draw()

{

  double width = getWidth();

  double height = getHeight();

  System.out.println(width + ";"+ height);

  GraphicsContext context = getGraphicsContext2D();

  context.clearRect(0, 0, width, height);

  context.setFill(Color.GREENYELLOW);

  context.fillRect(0, 0, width, height);

}

}

}

The interesting line being

canvas.heightProperty().bind(borderPane.heightProperty());

This works only halfway, when the window is getting bigger the draw functions all are called, but when the window gets tinier the draw function is not getting called.

Now I thought maybe I have to go higher in the hierarchy.

canvas.heightProperty().bind(tab.? tab has no heightProperty

One futher?

canvas.heightProperty.bind(tabPane.tabPane.heightProperty());

Now this looks good ( it works when it gets bigger or smaller ), until you realize that it always will be atleast 29 pixel big ( atleast on my system )

test.png

The reason being that the header is the missing 29 pixel. But I don't see a way to get the size of the header of the tabPane. Now I could just subtract 29 from the tabPane.heightProperty, but that will only work on my system, it might have a different size on other systems or javafx might change.

I looked up some other ways to get a resizable canvas, but stuff like creating a custom Pane and only putting the canvas in and overriding the layoutChildren method seems more like a hack than a intended solution.

I really would appreciate a way to resize my canvas on demand without going any further than the parent of my canvas ( the borderPane in my case ).

This post has been answered by bouye-JavaNet on Jul 21 2015
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 18 2015
Added on Jul 21 2015
1 comment
1,604 views