java动态菜单,大家看看可否优化
一般的,应用程序是需要记录用于最近打开的文件的.我在我的窗口类中写了一个方法
来实现这点,各位看看有没有什么问题?(功能是正确的,但不知有没有效率问题,内存泄漏等,或者有没有更好的办法)(这个方法在jbInit()中要调用,用于菜单初始化,然后每当用户成功打开一个文件也要调用):
public class MainFrame ....................
{
...............................
public void loadFileMenu()
{
//get the last 4 files users opened.The names of these files
//are recorded in app.history which will be serialized after
//the program exit.
java.util.Vector v=app.history.getRecentFiles();
if(v!=null && v.size()>0)
{
int i;
// fileMenu only contain recent files
this.fileMenu.removeAll();
for(i=0;i<v.size();i++)
{
JMenuItem item=new JMenuItem(""+(i+1)+": "+v.get(i));
this.fileMenu.add(item);
item.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String name=((JMenuItem)e.getSource()).getText();
name=name.substring(3);
File f=new File(name);
if(f.exists() && name.toLowerCase().endsWith(".wav"))
{
// communication with other objects
wd.notifyAllObservers(FILE_OPENED,f);
app.history.lastOpenDir=f.getPath();
// record opened file path in History class
// if successfully,then update filemenu
if(app.history.addRencentFile(f.getAbsolutePath)))
loadFileMenu();
}
}
});
}
}
v=null;
}