Ejemplo: fondo anchorpane con colorPicker
Code 1.1 changeBackground.fxml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);
}
}
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)