Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Overlap buttons/Text over an image with JavaFX 8?

Tags:

java

javafx

I am having trouble placing buttons/text over an image I am using with JavaFX 8.

I used an ImageViewer to place the image but I am unable to actually get the rest ON TOP of the image.

I am using setTranslateX,Y to move the button around but it never overlaps.

Please tell me how I can solve this issue.

import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.scene.text.Text;


public class Main extends Application{


    public static void main(String[] args)
    {
        Application.launch(args);
    }


    public void start(Stage stage) throws Exception {

        int x = 450;
        int y = 450;

        Image image = new Image("space.jpg",x,y, false, false);
        ImageView iv1 = new ImageView();
        iv1.setImage(image);
        iv1.setPreserveRatio(true);
        iv1.setFitHeight(x);
        iv1.setFitWidth(y);


        Text text = new Text("hello");
        text.setFont(Font.font ("Arial", 27));

        Button button = new Button("Hello");
        button.setTranslateX(10);
        button.setTranslateY(10);
        button.setContentDisplay(ContentDisplay.TOP);


        HBox root = new HBox();


        root.getChildren().add(iv1);
        root.getChildren().add(text);
        root.getChildren().add(button);


        Scene scene = new Scene(root,x,y);

        stage.setTitle("Space Blaster (New Game)");
        stage.setScene(scene);
        stage.show();

    }
}
like image 252
Tacent Avatar asked Jan 12 '15 23:01

Tacent


1 Answers

You can use a StackPane to overlay two nodes. For example:

Button button = new Button("Hello");
Text text = new Text("hello");

HBox hbox = new HBox();
hbox.getChildren().addAll(button, text); // button will be left of text

Image image = new Image("space.jpg",x,y, false, false);
ImageView iv1 = new ImageView();

StackPane stackPane = new StackPane();
stackPane.getChildren().addAll(iv1, hbox); // hbox with button and text on top of image view

HBox root = new HBox();
root.getChildren().add(stackPane);

// etc

Another approach is just to put the controls (button and text) in a pane of some kind (e.g. HBox), and then to use CSS to set a background image on the pane.

like image 114
James_D Avatar answered Sep 20 '22 08:09

James_D