JavaFX button background image

前端 未结 1 838
-上瘾入骨i
-上瘾入骨i 2020-12-21 18:39

I have problem with setting backgroundImage on button in JavaFX.

Image newGame = new Image(\"File:/CSS/nova_hra.png\");
BackgroundImage newGameBgr = new Bac         


        
相关标签:
1条回答
  • 2020-12-21 19:03

    You can do it via css. If your background.jpg is in a package testing, simply do this:

        package testing;
    
        import javafx.application.Application;
        import javafx.scene.Scene;
        import javafx.scene.control.Button;
        import javafx.scene.layout.Pane;
        import javafx.stage.Stage;
    
        public class Main extends Application {
    
            @Override
            public void start(Stage primaryStage) {
    
                try {
    
                    Pane root = new Pane();
    
                    Button button = new Button( "Click me!");
                    button.setStyle("-fx-background-image: url('/testing/background.jpg')");
    
                    root.getChildren().add(button);
    
                    Scene scene = new Scene(root, 800, 400);
                    primaryStage.setScene(scene);
                    primaryStage.show();
    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
            public static void main(String[] args) {
                launch(args);
            }
        }
    

    If you don't want to use css, you could do it like this:

            BackgroundImage backgroundImage = new BackgroundImage( new Image( getClass().getResource("/testing/background.jpg").toExternalForm()), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT);
            Background background = new Background(backgroundImage);
    
            Button button = new Button( "Click me!");
            button.setBackground(background);
    
    0 讨论(0)
提交回复
热议问题