Search code examples
javabuttonjavafxfxml

JavaFX Button with transparent background


I have some classical Button in JavaFX with a box containing some text.

I need buttons without that box, just the text, and when I hover the button or click on the button with mouse, it shall change its color to different.


Solution

  • In JavaFX styling is done by using CSS.

    .button{
        -fx-border-color: transparent;
        -fx-border-width: 0;
        -fx-background-radius: 0;
        -fx-background-color: transparent;
        -fx-font-family:"Segoe UI", Helvetica, Arial, sans-serif;
        -fx-font-size: 1em; /* 12 */
        -fx-text-fill: #828282;
    }
    
    .button:focused {
        -fx-border-color: transparent, black;
        -fx-border-width: 1, 1;
        -fx-border-style: solid, segments(1, 2);
        -fx-border-radius: 0, 0;
        -fx-border-insets: 1 1 1 1, 0;
    }
    
    .button:pressed {
        -fx-background-color: black;
        -fx-text-fill: white;
    }
    

    Add this code to a CSS file, save it to the directory where the source file of the control exists which contains you buttons. Then in this class:

    getStylesheets().add(getClass().getResource("nameofyourcssfile.css").toExternalForm());
    

    Then all of the buttons that that object contain will use this style-classes.

    Modification on your need is straightforward.

    Good tutorial to start: http://docs.oracle.com/javafx/2/css_tutorial/jfxpub-css_tutorial.htm