Answers for "anchorpane background with colorPicker"

0

anchorpane background with colorPicker

Code 1.1 changeBackground.fxml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
  
<?import javafx.scene.control.ColorPicker?>
<?import javafx.scene.layout.AnchorPane?>
  
  
<AnchorPane fx:id="anchorPane" fx:controller="sample.ChangeBGController" maxHeight="-Infinity" maxWidth="-Infinity"
            minHeight="-Infinity"
            minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1"
            xmlns:fx="http://javafx.com/fxml/1">
    <children>
        <ColorPicker fx:id="colorPicker" layoutX="14.0" layoutY="21.0"/>
    </children>
</AnchorPane>
In the fxml code above, there is only AnchorPane as the root layout and a ColorPicker to change the background color. Next up is the controller.

Code 1.2 ChangeBGController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import javafx.fxml.FXML;
import javafx.scene.control.ColorPicker;
import javafx.scene.layout.AnchorPane;
  
public class ChangeBGController {
  
    @FXML
    private AnchorPane anchorPane;
    @FXML
    private ColorPicker colorPicker;
  
    public void initialize() {
        colorPicker.valueProperty().addListener((observable -> {
            anchorPane.setStyle(
                    "-fx-background-color: #" + colorPicker.getValue().toString().substring(2, 8) + ";"
            );
        }));
    }
}
The controller code above will change the AnchorPane background whenever the ColorPicker value changes shown on the 13th line. Because the ColorPicker value is in the form of a literal hex (0xff), the ColorPicker value is only taken from the second to 8 characters seen from the substring () method.

Code 1.3 Main.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
  
public class Main extends Application {
  
    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("changeBackground.fxml"));
        primaryStage.setTitle("Change The Background Color");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }
  
  
    public static void main(String[] args) {
        launch(args);
    }
}
Posted by: Guest on May-06-2021

Code answers related to "anchorpane background with colorPicker"

Browse Popular Code Answers by Language