关于JavaFx中ListView的选择标记问题

咸鱼比较咸 2017-11-27 10:03:35
本人刚刚接触这些内容…真心菜,同时也真心求各位的指点!
具体问题如下:
在一个JavaFx的ListView中,我通过用户输入添加了几个items(用的是ObservableList),然后现在想要实现的是:
根据用户的输入,匹配到ListView中的某一个item,并将其标黑(就是标记就好,效果跟鼠标Select这个item一样)。
我能够匹配到具体的item,但是并不知道要怎么把它标黑…求教各位前辈和大佬…
...全文
418 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Font; import javafx.stage.Stage; import javafx.util.Callback; public class ListViewSample extends Application { ListView<String> list = new ListView<String>(); ObservableList<String> data = FXCollections.observableArrayList( "chocolate", "salmon", "gold", "coral", "darkorchid", "darkgoldenrod", "lightsalmon", "black", "rosybrown", "blue", "blueviolet", "brown"); final Label label = new Label(); @Override public void start(Stage stage) { VBox box = new VBox(); Scene scene = new Scene(box, 200, 200); stage.setScene(scene); stage.setTitle("ListViewSample"); box.getChildren().addAll(list, label); VBox.setVgrow(list, Priority.ALWAYS); label.setLayoutX(10); label.setLayoutY(115); label.setFont(Font.font("Verdana", 20)); list.setItems(data); list.setCellFactory(new Callback<ListView<String>, ListCell<String>>() { @Override public ListCell<String> call(ListView<String> list) { return new ColorRectCell(); } } ); list.getSelectionModel().selectedItemProperty().addListener( new ChangeListener<String>() { public void changed(ObservableValue<? extends String> ov, String old_val, String new_val) { label.setText(new_val); label.setTextFill(Color.web(new_val)); } }); stage.show(); } static class ColorRectCell extends ListCell<String> { @Override public void updateItem(String item, boolean empty) { super.updateItem(item, empty); Rectangle rect = new Rectangle(100, 20); if (item != null) { rect.setFill(Color.web(item)); setGraphic(rect); } } } public static void main(String[] args) { launch(args); } } 参考下这个例子,

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧