使用defaultcomboboxmodel和hashmap自动更新组合框

9lowa7mx  于 2021-06-27  发布在  Java
关注(0)|答案(0)|浏览(217)

我试图做一个组合框,我用hashmap。它通过从mysql数据库中选择相应的id来用name填充我的组合框。我正在链接下面的代码。我的问题是,当我向mysql表输入新数据时,组合框没有更新。我的程序运行在一个jframe和不同的面板中。我有一个面板,我从中向mysql表输入数据,在另一个面板中,我创建了一个组合框,它使用特定mysql表中的数据进行填充。

public class DB {
    Connection con=null;
    PreparedStatement pst;
    ResultSet rs;

    public static Connection dbconnect() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/accounting_software","root","dsgohel124");
            return conn;
        }
        catch (Exception e2) {
            System.out.println(e2);
            return null;
        } 
    }

    public HashMap<String, Integer> populateDropdown() {
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        Connection con = dbconnect();
        java.sql.Statement st;

        try {
            st=con.createStatement();
            rs=st.executeQuery("SELECT `acc_id`, `name` FROM `master_create`");
            DropdownItem di;

            while(rs.next()) {
                di = new DropdownItem(rs.getInt(1), rs.getString(2));
                map.put(di.getAccName(), di.getAccId());
            }
        }
        catch (Exception e3) {
            System.out.println(e3);
            return null;
        }
        return map;
    }
}
public void fromDropdown() {
        DB db = new DB();
        HashMap<String, Integer> map = db.populateDropdown();
        for(String fromKey : map.keySet()) {
            from_partyValue.addItem(fromKey);
        }
    }
JLabel from_party = new JLabel("From");
        from_party.setHorizontalAlignment(SwingConstants.RIGHT);
        from_party.setFont(new Font("Times New Roman", Font.BOLD, 22));
        from_party.setBounds(5, 170, 120, 20);
        TransictionCreate_panel.add(from_party);

        from_partyValue = new JComboBox<String>();
        from_partyValue.setModel(new DefaultComboBoxModel<String>(new String[] {"----Select----"}));
        from_partyValue.setFont(new Font("Arial", Font.PLAIN, 16));
        from_partyValue.setBounds(150, 162, 250, 28);
        TransictionCreate_panel.add(from_partyValue);

        fromDropdown();

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题