目录
题目:*16.16(使用ComboBox和ListView)
题目:*16.16(使用ComboBox和ListView)
编程一个程序,演示在列表中选择的条目。程序用组合框指定选择方式,如图16-43a所示。当选择条目后,列表下方的标签中就会显示选定项。
-
习题思路
- 创建一个HBox,新建一个ComboBox,内容为("MULTIPLE"和"SINGLE"),绑定在一个Label中。
- 新建一个ListView,在列表中添加几个国家的名字
- 创建一个BorderPane,将HBox设置在顶部,把ListView设置在中心
- 创建一个HBox,新建一个Text并添加到布局中。
- 为ComboBox注册一个事件,当事件被触发时,如果组合框内选择的是MULTIPLE,那么将ListView的选择模式设置为SelectionMode.MULTIPLE,SINGLE相同。
- 为listView注册事件,用getSelectionModel()方法获取到列表中的选中项(详细请看代码示例)
-
示例代码
编程练习题16_16UseComboBoxAndListView.java
package chapter_16;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class 编程练习题16_16UseComboBoxAndListView extends Application{
private Text text = new Text();
private String s = "";
private ListView<String> listView = new ListView<>();
@Override
public void start(Stage primaryStage) throws Exception {
String[] items = {"China","Japan","Korea","India", "Malaysia",
"Vitnam","Thailand", "Mongolia","France", "Bhutan","Malaysia"};
HBox hBox = new HBox();
hBox.setAlignment(Pos.CENTER);
ComboBox<String> cboMode = new ComboBox<String>();
cboMode.getItems().addAll("MULTIPLE","SINGLE");
cboMode.setValue("SINGLE");
Label lbMode = new Label("Choose Selection Mode:",cboMode);
lbMode.setContentDisplay(ContentDisplay.RIGHT);
hBox.getChildren().addAll(cboMode,lbMode);
HBox hBox2 = new HBox(text);
listView.getItems().addAll(items);
BorderPane borderPane = new BorderPane();
borderPane.setTop(hBox);
borderPane.setCenter(listView);
borderPane.setBottom(hBox2);
cboMode.setOnAction(e ->{
String value = cboMode.getValue();
if(value.equals("MULTIPLE"))
listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
else if (value.equals("SINGLE"))
listView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
});
listView.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
if (newSelection != null) {
ObservableList<String> selectedItems = listView.getSelectionModel().getSelectedItems();
if(cboMode.getValue().equals("SINGLE")) {
s = newSelection+" ";
}else if(cboMode.getValue().equals("MULTIPLE")) {
s = "";
for(String s2:selectedItems) {
s += s2+" ";
}
}
text.setText("Selected items are "+s);
selectedItems.forEach(System.out::println);//输出元素以便于检查
}
});
Scene scene = new Scene(borderPane,250, 150);
primaryStage.setTitle("编程练习题16_16UseComboBoxAndListView");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
-
结果展示