Joross Barredo
Joross Barredo

Reputation: 41

Custom JavaFX button shapes

I'm not a veteran coder of JavaFX and would like to ask. How do you make or set a different shape to a button in JavaFX? Buttons in default have these rounded rectangular shapes to them. I would like to make a button shaped like the image below, an L-shape button.

I have googled this topic for many times but still got no luck in finding the solution.

Can you help me please?

Image

Upvotes: 4

Views: 6454

Answers (4)

Giovanni Contreras
Giovanni Contreras

Reputation: 2569

Make a Path node clickable

You can make an L shape with Path node and make it clickable.

This is a single class javafx app you can try .

App.java

public class App extends Application {
    
    @Override
    public void start(Stage stage) {
        
        Path path = new Path(new MoveTo(0, 0), new HLineTo(200), new VLineTo(-100),
                new HLineTo(100), new VLineTo(-200), new HLineTo(0), new ClosePath());
        path.setFill(Color.AQUAMARINE);
        
        path.setOnMouseClicked((e) -> {
            System.out.println("do something");
        });
        
        var scene = new Scene(new StackPane(path), 640, 480);
        stage.setScene(scene);
        stage.show();
    }
    
    public static void main(String[] args) {
        launch();
    }
    
}

Result:

enter image description here

Upvotes: 0

tiemby
tiemby

Reputation: 19

There is a way to get rid of the gray background color. you can set it to tranparent then your button will be just the image. in your case it will be x.setStyle("-fx-background-color: transparent") x being your button.

Upvotes: 2

Dean
Dean

Reputation: 11

you can also use the -fx-shape CSS property to an SVG path string. By specifying a shape the region takes on that shape instead of a rectangle or rounded rectangle.

Upvotes: 1

Stevantti
Stevantti

Reputation: 504

Try making the image file of that shape and use the Node.setGraphic() method. Example:

public void start(Stage primaryStage){

String u = "http://www.clker.com/cliparts/9/1/5/2/119498475589498995button-red_benji_park_01.svg.med.png";
    Image i = new Image(u);
    Button x = new Button();
    x.setGraphic(new ImageView(i));
    BorderPane y = new BorderPane();
    y.setCenter(x);

    primaryStage.setScene(new Scene(y, 400, 400));
    primaryStage.show();
}

It will display a large red button. But use your image.

Upvotes: -1

Related Questions