JavaFX ComboBox的选中事项

参考1:https://blog.csdn.net/mexel310/article/details/37909205

参考2:https://blog.csdn.net/maosijunzi/article/details/43486441

目的:通过选择下拉框中的字体,更新字符串“JavaFX”的显示字体。

 1 import javafx.application.Application;
 2 import javafx.beans.value.ChangeListener;
 3 import javafx.beans.value.ObservableValue;
 4 import javafx.collections.FXCollections;
 5 import javafx.geometry.Insets;
 6 import javafx.scene.Node;
 7 import javafx.scene.Scene;
 8 import javafx.scene.control.ComboBox;
 9 import javafx.scene.control.Label;
10 import javafx.scene.control.Tooltip;
11 import javafx.scene.layout.BorderPane;
12 import javafx.scene.layout.StackPane;
13 import javafx.scene.text.Font;
14 import javafx.stage.Stage;
15 
16 public class MyJavaFX extends Application {
17 
18     @Override
19     public void start(Stage primaryStage) throws Exception {
20         // Create a pane to hold the label and the combo box
21         BorderPane pane = new BorderPane();
22         
23         // label
24         Label label = new Label();
25         label.setText("JavaFX");
26         
27         // combo box
28         ComboBox<Object> comboBox = new ComboBox<>();
29         comboBox.setTooltip(new Tooltip("Select the language"));
30         comboBox.setItems(FXCollections.observableArrayList(Font.getFamilies()));
31         comboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
32             @Override
33             public void changed(ObservableValue observable, Object oldValue, Object newValue) {
34                 System.out.println(newValue.toString());
35                 label.setFont(Font.font(newValue.toString()));
36                 
37             }
38         });
39         
40         // Place combo box in the top of the pane, and label in the bottom of the pane 
41         pane.setTop(new CustomPane(comboBox));
42         pane.setBottom(new CustomPane(label));
43         
44         Scene scene = new Scene(pane);
45         primaryStage.setTitle("Font Demo");
46         primaryStage.setScene(scene);
47         primaryStage.show();
48     }
49 
50     public static void main(String[] args) {
51         launch(args);
52     }
53 }
54 
55 class CustomPane extends StackPane {
56     public CustomPane(Node node) {
57         getChildren().add(node);
58         setStyle("-fx-border-color: green;");
59         setPadding(new Insets(20, 20, 20, 20));
60     }
61 }

运行效果:

 

原文地址:https://www.cnblogs.com/Satu/p/10802106.html