简体   繁体   English

问:如何从ComboBox的HashMap获取键值并将其保存到数据库

[英]Q: How to get key value from a HashMap of a ComboBox and save it to the database

I am trying to get the Key value of my HashMap from a ComboBox, but every time I use the variable of my ComboBox it just returns the name of the ComboBox: cmbCourse. 我试图从ComboBox中获取HashMap的Key值,但是每次我使用ComboBox的变量时,它只会返回ComboBox的名称:cmbCourse。 I want the code to get the key value and save it into my database. 我希望代码获取键值并将其保存到数据库中。

Here is my insertion code 这是我的插入代码

String query2 = ("INSERT INTO tblcourseinfo (user_id, course_id, school_id) VALUES (?,?,?)");
            QueryCourses qc = new QueryCourses();
            HashMap<String, Integer> map = qc.hashMap();
            stmt = conn.prepareStatement(query2);
            System.out.println(cmbCourse);
            System.out.println(cmbSchool);
            stmt.setInt(1, key);
            stmt.setObject(2, cmbCourse.getValue());
            stmt.setObject(3, cmbSchool.getValue());
            stmt.executeUpdate();

this is how I call the HashMap to populate the ComboBoxes 这就是我所谓的HashMap来填充ComboBoxes的方式

public void populateCourse() throws SQLException, ClassNotFoundException {
    QueryCourses qc = new QueryCourses();
    HashMap<String, Integer> map = qc.hashMap();

    cmbCourse.getItems().setAll(map.keySet());
}

public void populateSchool() throws SQLException {
    QuerySchools qs = new QuerySchools();
    HashMap<String, Integer> map = qs.hashMap();

    cmbSchool.getItems().setAll(map.keySet());
}

and here is the query to populate it 这是填充它的查询

public class QueryCourses {    
public static ArrayList<Courses> getCourses() throws ClassNotFoundException, SQLException {
    String queryCourses = "SELECT course_id, course_title FROM tblcourses";
    Connection conn = DbConnection.ConnectDB();
    Statement stmt = conn.createStatement();
    ResultSet rs;
    rs = stmt.executeQuery(queryCourses);
    ArrayList<Courses> courseList = new ArrayList<>();
    while (rs.next()) {
        Courses crse = new Courses(rs.getInt("course_id"), rs.getString("course_title"));
        courseList.add(crse);
    }
    return courseList;
}

public HashMap<String, Integer> hashMap() throws SQLException, ClassNotFoundException{
    HashMap<String, Integer> map = new HashMap<>();
    try {            
        for (Courses crse : getCourses()) {
            map.put(crse.getCourseTitle(), crse.getCourseId());
        }
    } catch (SQLException ex) {
        Logger.getLogger(NewStudentController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return map;
}
}

Focusing on the primary issue 专注于主要问题

How to get the ID of the selected item 如何获取所选商品的ID

This is most easily solved by not using a HashMap and instead, adding the Course object directly to the ComboBox ObservableList and changing the way that the items are rendered. 最简单的解决方法是不使用HashMap ,而是将Course对象直接添加到ComboBox ObservableList并更改项目的呈现方式。

In this way, you don't need to worry about providing lookups or other fancy pancy solutions, as all the information you need is stored in the Course object itself. 这样,您无需担心提供查找或其他奇特的解决方案,因为所需的所有信息都存储在Course对象本身中。

So, I don't have access to your code, so I had to make a few things up, starting with the Course object... 因此,我无权访问您的代码,因此我不得不从Course对象开始做一些事情……

public class Course {

    private long id;
    private String title;

    public Course(long id, String title) {
        this.id = id;
        this.title = title;
    }

    public long getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    @Override
    public String toString() {
        return "Course{" + "id=" + id + ", title=" + title + '}';
    }

}

When that in hand we can create a custom ListCell ... 在这种情况下,我们可以创建一个自定义ListCell ...

public class CourseCell extends ListCell<Course> {

    @Override
    protected void updateItem(Course item, boolean empty) {
        super.updateItem(item, empty);
        if (item != null) {
            setText(item.getTitle());
        } else {
            setText(null);
        }
    }
}

Then we need to apply the data and renderers together... 然后我们需要将数据和渲染器一起应用...

// I can imagine this been loaded from a ResultSet
ObservableList<Course> options = FXCollections.observableArrayList(
                new Course(0, "JavaFX"),
                new Course(1, "Swing"),
                new Course(2, "Objective C"),
                new Course(3, "Swift")
);
ComboBox<Course> comboBox = new ComboBox<Course>(options);
comboBox.setCellFactory(new Callback<ListView<Course>, ListCell<Course>>() {
    @Override
    public ListCell<Course> call(ListView<Course> courses) {
        return new CourseCell();
    }
});
comboBox.setButtonCell(new CourseCell());

Then at some point, we need to get the selected value... 然后在某个时候,我们需要获取选定的值...

Course course = comboBox.getValue();
if (course != null) {
    System.out.println(course);
    System.out.println(course.getId());
}

getValue will now return a Course object, including the title and id , convenient. getValue现在将返回一个Course对象,包括titleid ,很方便。

Remember, you're dealing with a OO language, where ever possible, maintain the encapsulation of the data, it just makes life so much simpler. 请记住,您正在使用一种面向对象的语言,只要有可能,就维护数据的封装,这只会使生活变得更加简单。

Runnable Example... 可运行的示例...

This is like only the third JavaFX app I've written, and most of it was gleamed from tutorials, other answers and some blogs, so forgive me any glaring mistakes, I tried to focus on the ListCell implementation 这就像我编写的第三个JavaFX应用程序一样,其中大部分内容来自教程,其他答案和一些博客,所以请原谅我任何明显的错误,我尝试着重于ListCell实现

ListCell实施

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.util.Callback;

public class Test extends Application {

    @Override
    public void start(Stage primaryStage) {

        GridPane gridPane = new GridPane();

        ObservableList<Course> options = FXCollections.observableArrayList(
                        new Course(0, "JavaFX"),
                        new Course(1, "Swing"),
                        new Course(2, "Objective C"),
                        new Course(3, "Swift")
        );
        ComboBox<Course> comboBox = new ComboBox<Course>(options);
        comboBox.setCellFactory(new Callback<ListView<Course>, ListCell<Course>>() {
            @Override
            public ListCell<Course> call(ListView<Course> courses) {
                return new CourseCell();
            }
        });
        comboBox.setButtonCell(new CourseCell());

        Button btn = new Button();
        btn.setText("Use");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                Course course = comboBox.getValue();
                if (course != null) {
                    System.out.println(course);
                    System.out.println(course.getId());
                }
            }
        });

        GridPane.setHalignment(comboBox, HPos.CENTER);
        GridPane.setHalignment(btn, HPos.CENTER);

        gridPane.setAlignment(Pos.CENTER);

        gridPane.add(comboBox, 0, 0);
        gridPane.add(btn, 0, 1);

        Scene scene = new Scene(gridPane, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    public class CourseCell extends ListCell<Course> {

        @Override
        protected void updateItem(Course item, boolean empty) {
            super.updateItem(item, empty);
            if (item != null) {
                setText(item.getTitle());
            } else {
                setText(null);
            }
        }
    }

    public class Course {

        private long id;
        private String title;

        public Course(long id, String title) {
            this.id = id;
            this.title = title;
        }

        public long getId() {
            return id;
        }

        public String getTitle() {
            return title;
        }

        @Override
        public String toString() {
            return "Course{" + "id=" + id + ", title=" + title + '}';
        }

    }

}

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

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