1

I have the following code for my JavaFX Button.

Button playButton = new Button("Play");
    playButton.setLayoutX(980);
    playButton.setLayoutY(rectangle.getLayoutY());
    playButton.setFont(new Font(45));
    playButton.setTextFill(Color.BLACK);
    playButton.setPrefSize(200, 125);
    playButton.setStyle("-fx-border-color:black;" + "-fx-border-width: 3 3 3 3");
    playButton.setBackground(new Background(blackJackBackgroundImage));
    playButton.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {

        }
    });
    m_layout.getChildren().add(playButton);

I want that when you hover over the button that the color of the text and the border turns gray. How can I do that?

S.Daineko
  • 1,790
  • 1
  • 20
  • 29
asdfasf
  • 23
  • 3
  • Move the styles to an external style sheet, and use the `:hover` pseudoclass to set the styles when the button is hovered. – James_D May 19 '20 at 11:23
  • @James_D does it not work to do it the way op is, or are you just suggesting that because it is better? I remember the fx and css has some weird caveats. – matt May 19 '20 at 13:15
  • 2
    With inline CSS you can only specify a list of *declarations*, not a *selector*. So you can't specifically select hovered buttons with inline CSS (you would have to register listeners and change the inline CSS when the button changed hover status, which gets hard to maintain very quickly). Use external CSS stylesheets so you can select the hovered pseudoclass. – James_D May 19 '20 at 13:18

1 Answers1

1

An example of styled button

package buttonhover;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;


public class ButtonHover extends Application {

@Override
public void start(Stage primaryStage) {
    Button btn = new Button();
    btn.setText("Button Hover");


    StackPane root = new StackPane();
    root.getChildren().add(btn);

    Scene scene = new Scene(root, 300, 250);
    scene.getStylesheets()
    .add(this.getClass().getResource("button.css").toExternalForm());
    primaryStage.setTitle("button");
    primaryStage.setScene(scene);
    primaryStage.show();
}


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

button.css

.button {  
-fx-border-color:black;
-fx-border-width: 3 3 3 3 ;  
}
.button .text {
-fx-fill:black;
 }
.button:hover .text{
-fx-fill: grey ;    


 }
 .button:hover {
 -fx-border-color: grey ;    

 }

enter image description here

hover

Giovanni Contreras
  • 2,345
  • 1
  • 13
  • 22