初始化组合框时抛出Java内存不足异常

时间:2010-02-13 16:07:47

标签: java jcombobox out-of-memory

这是我的代码,这里的变量bq是一个名为BasicQuery的自定义类,它返回一个JavaDB连接... AutoCompleteDecorator是来自swingX库的类,用于实现自动完成功能...这段代码当rus大约3次运行正常时但之后它会一直冻结,一段时间之后抛出内存异常!我无法找到问题所在。谁能帮帮我吗?如果您需要代码的其他部分,请告诉我们!

private void initCombos()
{
    ResultSet r=bq.executeQuery("select productID,productName from products");
    cmbProductID.removeActionListener(this);
    cmbProductID.removeActionListener(this);

    try
    {
        cmbProductID.removeAllItems();
        cmbProductName.removeAllItems();
        cmbCodes.removeAllItems();
        String s1;
        while(r.next())
        {
            s1=r.getString(1).trim();
            cmbProductID.addItem(s1);
            cmbCodes.addItem(s1);
            cmbProductName.addItem(r.getString(2).trim());
        }
        r.close();
        cmbProductID.addActionListener(this);
        cmbProductName.addActionListener(this);
        AutoCompleteDecorator.decorate(cmbProductID);
        AutoCompleteDecorator.decorate(cmbProductName);
    }
    catch(Exception x)
    {
        JOptionPane.showMessageDialog(this,"Error setting up ComboBoxes "+x);
    }
}

private void initCombos() { ResultSet r=bq.executeQuery("select productID,productName from products"); cmbProductID.removeActionListener(this); cmbProductID.removeActionListener(this); try { cmbProductID.removeAllItems(); cmbProductName.removeAllItems(); cmbCodes.removeAllItems(); String s1; while(r.next()) { s1=r.getString(1).trim(); cmbProductID.addItem(s1); cmbCodes.addItem(s1); cmbProductName.addItem(r.getString(2).trim()); } r.close(); cmbProductID.addActionListener(this); cmbProductName.addActionListener(this); AutoCompleteDecorator.decorate(cmbProductID); AutoCompleteDecorator.decorate(cmbProductName); } catch(Exception x) { JOptionPane.showMessageDialog(this,"Error setting up ComboBoxes "+x); } }

2 个答案:

答案 0 :(得分:2)

在本节中:

ResultSet r=bq.executeQuery("select productID,productName from products");
cmbProductID.removeActionListener(this);
cmbProductID.removeActionListener(this);

我认为你的意思是:

ResultSet r=bq.executeQuery("select productID,productName from products");
cmbProductID.removeActionListener(this);
cmbProductName.removeActionListener(this);

否则会在cmbProductName上打开一个会泄漏内存的事件处理程序。

答案 1 :(得分:2)

我看到有两个问题。 @Nick Carver指出了一个(+1)。如果您不想从cmbProductName中删除ActionListener,那么您将在ResultSet上的每次迭代中传播该组合中的动作事件。

第二个是你在绘画线中似乎做了一些繁重的工作。您的数据库调用通常应该在工作线程中进行,并且只有绘制gui的任务才能在绘制线程中完成。否则你将阻止这个线程,你的应用程序将感到迟钝。在SwingWorker中查看Swing for more info on this topic和并发概念。