简体   繁体   English

在列表视图上显示 hashmap 键,然后单击显示 hashmap 值的对话框

[英]Showing hashmap key on a listview and on click show a dialog of hashmap value

I have a table named restaurants.我有一张名为餐馆的桌子。 It has a filed 'name' and 'location'.它有一个归档的“名称”和“位置”。 I wanna create a listView where I show all the names of restaurants, but on click of a listView item, I wanna show an alert(dialog) with its location.我想创建一个列表视图,在其中显示所有餐厅的名称,但是在单击列表视图项目时,我想显示一个警报(对话框)及其位置。 I have saved the data from the database in a HashMap but on alert, it shows the name of the restaurant.我已将数据库中的数据保存在 HashMap 中,但在警报中,它显示了餐厅的名称。 How can I show the location?如何显示位置? Here is my code:这是我的代码:

 public void populateData() throws SQLException {
        Connection c = DriverManager.getConnection("jdbc:sqlite:src/main/resources/com/example/database/SmartCity.db");
        Statement stmt = c.createStatement();
        String sql = "SELECT * FROM restaurants";
        ResultSet rs = stmt.executeQuery(sql);
        HashMap<String,String> restaurants = new HashMap<>();
        while (rs.next()){
            restaurants.put(rs.getString("name"),rs.getString("location"));
        }
        rs.close();
        stmt.close();
        for(String restaurant : restaurants .keySet()){
            restaurantList.getItems().add(restaurant);
        }
    }

    public void handleItemClick(){
        restaurantList.setOnMouseClicked(mouseEvent -> {
            String selectedItem = restaurantList.getSelectionModel().getSelectedItem().toString();
            System.out.println(restaurantList.getSelectionModel());
            Dialog d = new Alert(Alert.AlertType.INFORMATION,selectedItem);
            d.show();
        });

    }

This is strictly my option, but I think you're going about it the wrong way.这完全是我的选择,但我认为你的做法是错误的。 Here's how I would do it:这是我的做法:

  1. Create a Restaurant with fields for Name and Location.使用名称和位置字段创建餐厅。
  2. Instead of loading into a map, create Restaurant objects and add those to the ListModel与其加载到 map 中,不如创建 Restaurant 对象并将其添加到 ListModel
  3. Create ListCellRenderer by extending DefaultListCellRenderer, calling super.getListCellRendererComponent, and then setting the text to that of the item.name.通过扩展 DefaultListCellRenderer,调用 super.getListCellRendererComponent,然后将文本设置为 item.name 的文本来创建 ListCellRenderer。
  4. On the item click handler you get the name from the selectedItem, cast it to Restaurant, and then get the location from that.在项目单击处理程序上,您从 selectedItem 获取名称,将其转换为 Restaurant,然后从中获取位置。

Edit: The benefit to extra work is if you ever add information to the Restaurant (type of food, number of yelp star, distance from user, etc), you can modify your renderer display that information.编辑:额外工作的好处是,如果您向餐厅添加信息(食物类型、yelp 星数、与用户的距离等),您可以修改渲染器显示该信息。 You can add icons, change background color, etc.您可以添加图标、更改背景颜色等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM