Question

I dont know how to discribe this Problem. I want to set a Textobject in the middle of a cell (gridpane) with a rectangle in the background. Dont know how to do this or search for the right word for this problem. Hope someone will help me. :-)

Thats my code for now:

void AbtButton(String Abteil) {

    Rectangle r = new Rectangle();

    r.setWidth(80);
    r.setHeight(40);
    r.setArcWidth(20);
    r.setArcHeight(20);
    r.setFill(Color.AQUAMARINE);
    r.setStroke(Color.BLACK);
    r.setStrokeWidth(2);;
    r.toBack();

    Text abt = new Text(Abteil);
    abt.setId(Abteil);
    abt.setFont(Font.font ("Verdana", FontWeight.BOLD, 20));
    abt.setTextAlignment(TextAlignment.CENTER);
    abt.toFront();

    Button.getChildren().addAll(r,abt); 
  }

if I make

gridpane.add(r, 1, 1);
gridpane.add(abt, 1, 1);

it shows me the correct picture and fills the cell with the rectangle and the text is in the center position.

with

Button.getChildren().addAll(r,abt); 

the Textobject is on the wrong position namely above the rectantangle and that shouldn't be, but i need this. later i want to create a lot of this grouped objects.

toBack() and toFront() doesn't work here too :-(

edit:

here i have a picture of the Problem.

http://s14.directupload.net/file/d/3449/blgrlw63_jpg.htm

The z-order of the text should be in front and the rectangle in back in this gridpane. With this code

abt.setLayoutX(27);
abt.setLayoutY(27);

it is possible to set the Position of the text but is not a good option.

Was it helpful?

Solution

You can use the StackPane class to solve your problem. Have a look at the following code:

 GridPane g1 = new GridPane();

    StackPane sp = new StackPane();
    Rectangle r = new Rectangle(100, 100);
    r.setFill(Color.AQUA);
    Text t = new Text("StackOverFlow");

    sp.getChildren().addAll(r,t);

    g1.add(sp, 0, 0);

    Scene sc = new Scene(g1,200,200);
    primaryStage.setScene(sc);
    primaryStage.show();

The stackpane works in the "last in -- first out" way. So your last added child is the first to display (or better: the element on top of the pane). Any following children will be placed behind the first child.

To solve your problem, create a stackpane, then put the rectangle in it, and then the text. After that, put the stackpane in the desired position on the gridpane.

OTHER TIPS

You should use Hbox instead of Rectangle because there is no property to set text into Rectangle shape.

    gridFirst.setGridLinesVisible(true);
    hboxFirst.setStyle("-fx-background-color:green");
    hboxFirst.setAlignment(Pos.CENTER);
    hboxFirst.getChildren().add(new Text("hello"));

enter image description here

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top