简体   繁体   English

在另一个JComboBox中选择一个项目时如何显示JComboBox

[英]How to display a JComboBox when an item is selected in another JComboBox

I'm trying to display values in JComboBox B when I select items from JComboBox A . 当我从JComboBox A选择项目时,我试图在JComboBox B显示值。 So far, nothing happened when I select a value from JComboBox A . 到目前为止,当我从JComboBox A选择一个值时,什么都没有发生。 Here is my data and code. 这是我的数据和代码。 So for instance, if I select 1 from my JComboBox A (paperid), my result in JComboBox B (authorid) will be 1,2,4. 因此,例如,如果我从JComboBox A (paperid)中选择1,则在JComboBox B (authorid)中的结果将为1,2,4。

在此处输入图片说明

在此处输入图片说明 JComboBox A

在此处输入图片说明 JComboBox B

private void comboboxAPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { 

    String display = (String) comboboxA.getSelectedItem();
    String sql = "Select authorid from submission where paperid =?";

    try {
        ps=conn.prepareStatement(sql);
        ps.setString(1,display);
        rset = ps.executeQuery();

        if (rset.next()){
               String add1 = rset.getString("authorid");
               System.out.println(add1);
               comboboxB.setSelectedItem(add1);
        }

    } catch(Exception e) {
        JOptionPane.showMessageDialog(null,e);
    }
 }

I think that I've understood your question at last. 我想我终于明白了您的问题。 You want the result of the query to be charged in the second combobox, don't you? 您希望在第二个组合框中收取查询结果,不是吗?

If that's the case, try this 如果是这样,请尝试

 private void comboboxAPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { 

    String display = (String) comboboxA.getSelectedItem();
    String sql = "Select authorid from submission where paperid =?";

    comboboxB.removeAllItems(); // <- Clear comboboxB

    try {
        ps = conn.prepareStatement(sql);
        ps.setString(1, display);
        rset = ps.executeQuery();

        while (rset.next()) {  // <- Include all authors found
           String add1 = rset.getString("authorid");
           System.out.println(add1);
           comboboxB.addItem(add1);
        }

   } catch(Exception e) {
        JOptionPane.showMessageDialog(null,e);
   }
}

Maybe you have to force a repaint in the container where the JComboBoxes are displayed after the execution of this method. 执行此方法后,可能必须在显示JComboBoxes的容器中强制进行重新绘制。 "myContainer" is not the variable name, replace with the name of your panel or your frame. "myContainer"不是变量名称,请替换为面板或框架的名称。

   myContainer.revalidate(); 
   myContainer.repaint();

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

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