使用Swing从侦听器添加Combobox值

时间:2014-10-15 12:46:32

标签: java swing jcombobox

我是Swing的新手。我有一个要求,我需要从数据库中获取数据并弹出组合框,当组合框监听器执行时,它需要加载值。我不确定我在哪里出错了以下代码中的值没有显示。 如果我错了,请任何人纠正我。 代码:

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;

public class ComboBoxSelectionChange extends JFrame
{
    public ComboBoxSelectionChange ()
    {
        initialize();
    }

    private void initialize ()
    {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JComboBox comboBox = new JComboBox();
        comboBox.setEditable(true);
        final JTextArea textArea = new JTextArea(5, 15);
        textArea.setBorder(new BevelBorder(BevelBorder.LOWERED));

        comboBox.addItemListener(new ItemListener() {

            public void itemStateChanged (ItemEvent event)
            {
                String[] items = { "A", "B", "C", "D", "E", "F" };
                final DefaultComboBoxModel model = new DefaultComboBoxModel(
                        items);

                comboBox.setModel(model);

            }
        });

        getContentPane().add(comboBox);
        getContentPane().add(textArea);
    }

    public static void main (String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            public void run ()
            {
                new ComboBoxSelectionChange().setVisible(true);
            }
        });
    }
}

3 个答案:

答案 0 :(得分:1)

尝试将弹出菜单监听器添加到JComboBox,如:

comboBox.addPopupMenuListener( PopupMenuListener listener )
{

   protected void popupMenuWillBecomeVisible( PopupMenuEvent event )
   {
       //update your model
   }

}

答案 1 :(得分:0)

您将阵列添加到jcombobox comboBox.addItem(items);,但是在重新分配jcombobox JComboBox comboBox = (JComboBox) event.getSource();之后。我相信您希望在初始化后添加项目。

使用模型添加商品以保存数据。

DefaultComboBoxModel m= new DefaultComboBoxModel(items)); comboBox.setModel(m);

答案 2 :(得分:0)

如果我正确地阅读了您的要求,您是否要等待加载组合列表,直到他们点击组合的下拉箭头为止?

[Keep in mind, this is not a typical way of loading a combobox]

如果是这样,几年前我有类似的要求,那个camickr帮助我解决了问题(回到旧的Sun论坛上)。

这个想法是来自表单其他地方的用户输入将驱动组合的项目列表。导出此列表将是一个昂贵的数据库查询,因此我们不想在每次更改用户输入时执行此操作。我们也不想要一个单独的"构建列表"按钮。

import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

/*
 * https://community.oracle.com/thread/2225626
 */
@SuppressWarnings("all")
public class DelayedComboBoxDemo implements Runnable
{
  private JCheckBox chkA, chkB, chkC;
  private JComboBox cboItems;
  private JFrame frame;

  public static void main(String[] args)
  { 
    SwingUtilities.invokeLater(new DelayedComboBoxDemo());
  }

  public void run()
  {
    chkA = new JCheckBox("A");
    chkB = new JCheckBox("B");
    chkC = new JCheckBox("C");

    cboItems = new JComboBox();
    cboItems.setPrototypeDisplayValue("X");

    JPanel p = new JPanel();
    p.add(chkA);
    p.add(chkB);
    p.add(chkC);
    p.add(cboItems);

    frame = new JFrame("Delayed ComboBox Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(p);
    frame.setSize(300, 100);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    cboItems.addPopupMenuListener(new PopupMenuListener()
    {
      public void popupMenuCanceled(PopupMenuEvent e) {}
      public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}

      public void popupMenuWillBecomeVisible(PopupMenuEvent e)
      {
        rebuildList();
      }
    });
  }

  private void rebuildList()
  {
    int oldCount = cboItems.getItemCount();

    frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

    // simulate a long transaction
    try
    {
      Thread.sleep(200);
    }
    catch (InterruptedException ex) {}

    // for testing purposes, just create the list here
    Vector<String> items = new Vector<String>();
    items.add("");

    if (chkA.isSelected()) { items.add("A"); }
    if (chkB.isSelected()) { items.add("B"); }
    if (chkC.isSelected()) { items.add("C"); }

    cboItems.setModel(new DefaultComboBoxModel(items));

    /*
     * Workaround if using Java 5 or early Java 6. Should be fixed in 6u25.
     * See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4743225 
     */
    if (oldCount != cboItems.getItemCount())
    {
      cboItems.hidePopup();
      cboItems.showPopup();
    }

    frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  }
}