如何使用swing永久存储最近的项目

时间:2014-11-05 09:42:50

标签: java swing permanent recent-file-list

我想将最近打开的文件添加到最近的菜单中。我做了那个任务。但是,它没有永久存储。这意味着当我关闭正在运行的应用程序时,最近的项目也被删除。我想存储最近的项目永久,在重新运行应用程序后,最近打开的项目可用。

我的代码:

public class RecentItems extends javax.swing.JFrame {
int i=0;
Queue<String> q;
JMenuItem item;
String recentPath;
int recentItems_count=0;
JTextPane textPane;
JScrollPane scrollPane;
public RecentItems() {
    initComponents();
    q=new LinkedList<>();
    textPane=new JTextPane();
    scrollPane=new JScrollPane(textPane);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    tp = new javax.swing.JTabbedPane();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    openAction = new javax.swing.JMenuItem();
    recentItems = new javax.swing.JMenu();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jMenu1.setText("File");

    openAction.setText("OPEN");
    openAction.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            openActionActionPerformed(evt);
        }
    });
    jMenu1.add(openAction);

    recentItems.setText("Recent");
    jMenu1.add(recentItems);

    jMenuBar1.add(jMenu1);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        

private void openActionActionPerformed(java.awt.event.ActionEvent evt) {                                           
    FileDialog fd = new FileDialog(RecentItems.this, "Select File", FileDialog.LOAD);
    fd.setVisible(true);
    String title;
    String sts;
    File file;
    if (fd.getFile() != null) {
        sts = fd.getDirectory() + fd.getFile();
        file=new File(sts);
        title=fd.getFile();
        JInternalFrame internalFrame = new JInternalFrame("",true,true); 
        i++;
        internalFrame.setName("Doc "+i);
        internalFrame.setTitle(title);
        try {
            internalFrame.setSelected(true);
        } 
        catch (PropertyVetoException ex) {
            Logger.getLogger(RecentItems.class.getName()).log(Level.SEVERE, null, ex);
        }      
        internalFrame.add(scrollPane);
        tp.add(internalFrame);
        try{
            tp.setSelectedIndex(i-1);  
        }
        catch(IndexOutOfBoundsException ioe){   
        }
        try {
            textPane.setPage(file.toURI().toURL());
        } 
        catch (MalformedURLException ex) {
            Logger.getLogger(RecentItems.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex) {
            Logger.getLogger(RecentItems.class.getName()).log(Level.SEVERE, null, ex);
        }
        setVisible(true);
        textPane.setCaretPosition(0);
        q.add(sts);
        recentItems_count++;              
        if(recentItems_count>1) {
            int size=q.size();
            String[] strArray = new String[q.size()];
            q.toArray(strArray);
            for(int k=0;k<size;k++) {
                for(int i=size-1;i>k;i--) {
                    if(strArray[k].equals(strArray[i])) {  
                        q.remove(strArray[k]); 
                        tp.remove(internalFrame);
                    }
                }
            }
        } 
        if(q.size()<=3) {
            recentItems.removeAll();
            for( String string : q) {  
                item=recentItems.add(string);
                recentPath=item.getText();
            }
        }
        else if(q.size()>3) {
            q.remove();
            recentItems.removeAll();
            for( String string : q)  {
                item=recentItems.add(string);
                recentPath=item.getText();
            }
        }
    }
}                                          

public static void main(String args[]) {
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(RecentItems.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(RecentItems.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(RecentItems.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(RecentItems.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new RecentItems().setVisible(true);
        }
    });
}                    
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem openAction;
private javax.swing.JMenu recentItems;
private javax.swing.JTabbedPane tp;                
}

2 个答案:

答案 0 :(得分:4)

您应该使用Java Preferences API以简单且跨平台的方式存储用户首选项。

步骤:

  • 定义首选项对象:
    Preferences prefs = Preferences.userNodeForPackage(yourpackagename.class);

  • 设置参考的键名称
    final String PREF_NAME = "recent_items";

  • 将值放在首选项中 prefs.put(PREF_NAME, value);

  • 检索与此首选项节点中指定键关联的值
    String propertyValue = prefs.get(PREF_NAME, yourDefaultValue);

代码:

将其添加到您的示例后:

package com.example;

public class Test extends javax.swing.JFrame  implements ActionListener {

    int i = 0;
    Queue<String> q;
    JMenuItem item;
    String recentPath;
    int recentItems_count = 0;
    JTextPane textPane;
    JScrollPane scrollPane;

    // Retrieve the user's preference node for this package
    Preferences prefs = Preferences.userNodeForPackage(com.example.Test.class);

    // key name of the preference
    final String PREF_NAME = "recent_items";
    private List<String> itemsAll = new ArrayList<String>();

    public Test() {
        initComponents();
        q = new LinkedList<>();
        textPane = new JTextPane();
        scrollPane = new JScrollPane(textPane);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        tp = new javax.swing.JTabbedPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        openAction = new javax.swing.JMenuItem();
        recentItems = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jMenu1.setText("File");

        openAction.setText("OPEN");
        openAction.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openActionActionPerformed(evt);
            }
        });
        jMenu1.add(openAction);

        recentItems.setText("Recent");
        jMenu1.add(recentItems);

        loaditemsFromPreferences();
        for (String item : itemsAll) {
            JMenuItem newMenuItem = recentItems.add(item);
            newMenuItem.addActionListener(this);
        }

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
                getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addComponent(tp,
                javax.swing.GroupLayout.Alignment.TRAILING,
                javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE));
        layout.setVerticalGroup(layout.createParallelGroup(
                javax.swing.GroupLayout.Alignment.LEADING).addComponent(tp,
                javax.swing.GroupLayout.Alignment.TRAILING,
                javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE));

        pack();
    }// </editor-fold>

    private JInternalFrame loadFile(String sts, String title) {
        File file = new File(sts);
        JInternalFrame internalFrame = new JInternalFrame("", true, true);
        i++;
        internalFrame.setName("Doc " + i);
        internalFrame.setTitle(title);
        try {
            internalFrame.setSelected(true);
        } catch (PropertyVetoException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
        internalFrame.add(scrollPane);
        tp.add(internalFrame);
        try {
            tp.setSelectedIndex(i - 1);
        } catch (IndexOutOfBoundsException ioe) {
        }
        try {
            textPane.setPage(file.toURI().toURL());
        } catch (MalformedURLException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
        setVisible(true);
        textPane.setCaretPosition(0);
        q.add(sts);
        return internalFrame;
    }

    private void openActionActionPerformed(java.awt.event.ActionEvent evt) {
        FileDialog fd = new FileDialog(Test.this, "Select File",
                FileDialog.LOAD);
        fd.setVisible(true);
        if (fd.getFile() != null) {
            String sts = fd.getDirectory() + fd.getFile();
            String title = fd.getFile();
            JInternalFrame internalFrame = loadFile(sts, title);
            recentItems_count++;
            if (recentItems_count > 1) {
                int size = q.size();
                String[] strArray = new String[q.size()];
                q.toArray(strArray);
                for (int k = 0; k < size; k++) {
                    for (int i = size - 1; i > k; i--) {
                        if (strArray[k].equals(strArray[i])) {
                            q.remove(strArray[k]);
                            tp.remove(internalFrame);
                        }
                    }
                }
            }

            if (q.size() <= 3) {
                recentItems.removeAll();
                itemsAll.clear();
                for (String string : q) {
                    item = recentItems.add(string);
                    recentPath = item.getText();
                    itemsAll.add(recentPath);
                    storeToPreferences();
                }
            } else if (q.size() > 3) {
                q.remove();
                recentItems.removeAll();
                itemsAll.clear();
                for (String string : q) {
                    item = recentItems.add(string);
                    recentPath = item.getText();
                    itemsAll.add(recentPath);
                    storeToPreferences();
                }
            }
        }
    }

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
                    .getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Test.class.getName()).log(
                    java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Test.class.getName()).log(
                    java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Test.class.getName()).log(
                    java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Test.class.getName()).log(
                    java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Test().setVisible(true);
            }
        });
    }

    private void loaditemsFromPreferences() {
        for (int i = 0; i < maxItems; i++) {
            String value = prefs.get(PREF_NAME + i, "");
            if (!value.equals("")) {
                itemsAll.add(value);
            } else {
                break;
            }
        }
    }

    private void storeToPreferences() {
        for (int i = 0; i < maxItems; i++) {
            if (i < itemsAll.size()) {
                prefs.put(PREF_NAME + i, (String) itemsAll.get(i));
            } else {
                prefs.remove(PREF_NAME + i);
            }
        }
    }


    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem openAction;
    private javax.swing.JMenu recentItems;
    private javax.swing.JTabbedPane tp;
    private final int maxItems = 3;

    public void actionPerformed(ActionEvent e) {
        System.out.println("Selected: " + e.getActionCommand());
        loadFile(e.getActionCommand(), e.getActionCommand());
    }
}

相关文档:

替代解决方案:

  

您可能希望使用PersistenceServiceJava Web Start的一项功能“提供在客户端系统上本地存储数据的方法,即使对于在受限执行环境中运行的应用程序也是如此。”可以找到相关示例herehere

答案 1 :(得分:0)

好吧,您应该将最近的文件存储在数据库或属性中。

Here是如何使用属性文件解决此问题的示例。