初始化组合框时抛出的Java内存不足异常
这是我的代码,这里变量bq是一个名为BasicQuery的自定义类,它返回一个JavaDB连接... AutoCompleteDecorator是来自swingX库的用于实现自动完成功能的类。 ..这段代码当rus大约3次运行正常,但在此之后它会一直冻结,并在一段时间后抛出内存异常!我找不到问题在哪里。谁能帮帮我吗?此外,如果您需要代码的其他部分,请让我知道!初始化组合框时抛出的Java内存不足异常
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);
}
}
我看到有两个问题。 @Nick Carver指出了一点(+1)。如果您不打算从cmbProductName
中移除ActionListener,那么您将在每次迭代中通过该组合在您的ResultSet
中传播动作事件。
第二个是你看起来在画线中做了一些繁重的工作。你的数据库调用通常应该在一个工作线程中进行,并且只有在绘制线程中绘制GUI的任务。否则,你会阻止这个线程,你的应用程序会感觉迟缓。在Swing for more info on this topic中查看SwingWorker和并发概念。
在本节:
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
这将导致内存泄漏。
谢谢尼克。我发现问题这是SwingX库。 AutoCompleteDecorator.decorate(cmbProductID); AutoCompleteDecorator.decorate(cmbProductName); – Thihara 2010-02-14 07:19:25
谢谢akf。我发现问题这是SwingX库。 AutoCompleteDecorator.decorate(cmbProductID); AutoCompleteDecorator.decorate(cmbProductName); 而我不知道SwingWorker和相关的方法/我会研究它... – Thihara 2010-02-14 07:18:52