Java 如何打开最近添加到Swing菜单中的文件?

Java 如何打开最近添加到Swing菜单中的文件?,java,swing,file-io,io,jtextarea,Java,Swing,File Io,Io,Jtextarea,当我打开文件中添加到“最近使用”菜单的文件时,但当我单击“最近使用”菜单的“添加路径”时,它将打开。怎么做 这是我的密码: public class RecentItemList extends javax.swing.JFrame { JTextArea tx; int i=0; int recentItems_count=0; String filename; String recentItem; Queue<String> q;

当我打开文件中添加到“最近使用”菜单的文件时,但当我单击“最近使用”菜单的“添加路径”时,它将打开。怎么做

这是我的密码:

public class RecentItemList extends javax.swing.JFrame {

    JTextArea tx;
    int i=0;
    int recentItems_count=0;
    String filename;
    String recentItem;
    Queue<String> q;
    public RecentItemList() {
        q=new LinkedList<>();
        initComponents();
    }


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

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

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jMenu1.setText("File");



        open.setText("Open");
        open.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openActionPerformed(evt);
            }
        });
        jMenu1.add(open);

        recentItems.setText("Recent Items.....");
        recentItems.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                recentItemsActionPerformed(evt);
            }
        });
        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 openActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openActionPerformed

           FileDialog fd = new FileDialog(RecentItemList.this, "Select File", FileDialog.LOAD);
           fd.show();
           String title;
           String sts;
           if (fd.getFile() != null) {
           sts = fd.getDirectory() + fd.getFile();
           title=fd.getFile();
           System.out.println("title :"+sts);
           BufferedReader br = null;
           StringBuffer str = new StringBuffer("");
             try {
                br = new BufferedReader(new FileReader(sts));
                String line;
             try {
                        while ((line = br.readLine()) != null) {
                        str.append(line + "\n");
                    }
                    } catch (IOException ex) {
                    Logger.getLogger(RecentItemList.class.getName()).log(Level.SEVERE, null, ex);
                }
                } catch (FileNotFoundException ex) {
                Logger.getLogger(RecentItemList.class.getName()).log(Level.SEVERE, null, ex);
            }
         String t = str.toString();
         final JInternalFrame internalFrame = new JInternalFrame("",true,true);  
        tx = new JTextArea();
        internalFrame.add(tx);
        i+=1;
        internalFrame.setName("Document"+i);
        internalFrame.setTitle(title);
        tp.add(internalFrame);
        internalFrame.setVisible(true);
             internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
        @Override
        public void internalFrameClosing(InternalFrameEvent e) {
            tp.remove(internalFrame);
        }
    });
            tx.setText(t);
            q.add(sts);
            recentItems.add(sts);
            recentItems_count++;

         if(recentItems_count>2){
             recentItem=(String)q.remove();
             recentItems.removeAll();
            // recentItems_count--;
             for (String string : q) {

                   recentItems.add(string);
             }

         }

                try {
                br.close();
                } 
             catch (IOException ex) {
                Logger.getLogger(RecentItemList.class.getName()).log(Level.SEVERE, null, ex);
            }
}
    }



    private void recentItemsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_recentItemsActionPerformed
        Object[] selectedObjects = recentItems.getSelectedObjects();
        System.out.println(selectedObjects);

    }//GEN-LAST:event_recentItemsActionPerformed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        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(RecentItemList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(RecentItemList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(RecentItemList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RecentItemList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new RecentItemList().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem create;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem open;
    private javax.swing.JMenu recentItems;
    private javax.swing.JMenuItem save;
    private javax.swing.JTabbedPane tp;
    // End of variables declaration//GEN-END:variables

}
公共类RecentItemList扩展了javax.swing.JFrame{
jtext区域tx;
int i=0;
int recentItems_count=0;
字符串文件名;
字符串接收项;
队列q;
公共RecentItemList(){
q=新的LinkedList();
初始化组件();
}
@抑制警告(“未选中”)
////GEN-BEGIN:初始化组件
私有组件(){
tp=newjavax.swing.JTabbedPane();
jMenuBar1=newjavax.swing.JMenuBar();
jMenu1=newjavax.swing.JMenu();
create=newjavax.swing.JMenuItem();
save=newjavax.swing.JMenuItem();
open=newjavax.swing.JMenuItem();
recentItems=newjavax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setText(“文件”);
open.setText(“open”);
open.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
执行的开放操作(evt);
}
});
jMenu1.add(打开);
setText(“最近的项目…”);
recentItems.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
执行的最近事项(evt);
}
});
jMenu1.添加(最近项);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout=newjavax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp,javax.swing.GroupLayout.Alignment.TRAILING,javax.swing.GroupLayout.DEFAULT\u SIZE,400,Short.MAX\u值)
);
layout.setVerticalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp,javax.swing.GroupLayout.Alignment.TRAILING,javax.swing.GroupLayout.DEFAULT\u SIZE,279,Short.MAX\u值)
);
包装();
}// 
私有void openActionPerformed(java.awt.event.ActionEvent evt){//GEN-FIRST:event\u openActionPerformed
FileDialog fd=新建FileDialog(RecentItemList.this,“选择文件”,FileDialog.LOAD);
fd.show();
字符串标题;
字符串sts;
如果(fd.getFile()!=null){
sts=fd.getDirectory()+fd.getFile();
title=fd.getFile();
System.out.println(“标题:+sts”);
BufferedReader br=null;
StringBuffer str=新的StringBuffer(“”);
试一试{
br=新的BufferedReader(新的文件读取器(sts));
弦线;
试一试{
而((line=br.readLine())!=null){
str.append(第+行“\n”);
}
}捕获(IOEX异常){
Logger.getLogger(RecentItemList.class.getName()).log(Level.SEVERE,null,ex);
}
}捕获(FileNotFoundException ex){
Logger.getLogger(RecentItemList.class.getName()).log(Level.SEVERE,null,ex);
}
字符串t=str.toString();
最终JInternalFrame internalFrame=新JInternalFrame(“”,true,true);
tx=新的JTextArea();
内部帧添加(tx);
i+=1;
internalFrame.setName(“文件”+i);
internalFrame.setTitle(title);
tp.add(内部框架);
internalFrame.setVisible(true);
addInternalFrameListener(新的InternalFrameAdapter(){
@凌驾
公共无效internalFrameClosing(InternalFrameEvent e){
移除(内部框架);
}
});
tx.setText(t);
q、 添加(sts);
最近添加(sts);
最近项目数++;
如果(最近项计数>2){
recentItem=(字符串)q.remove();
recentItems.removeAll();
//最近数--;
for(字符串:q){
recentItems.add(字符串);
}
}
试一试{
br.close();
} 
捕获(IOEX异常){
Logger.getLogger(RecentItemList.class.getName()).log(Level.SEVERE,null,ex);
}
}
}
私有void recentItemsActionPerformed(java.awt.event.ActionEvent evt){//GEN-FIRST:event\u recentItemsActionPerformed
Object[]selectedObjects=recentItems.getSelectedObjects();
System.out.println(选择的对象);
}//GEN-LAST:已执行事件\接收项
公共静态void main(字符串参数[]){
/*设置Nimbus的外观和感觉*/
//
/*如果Nimbus(在JavaSE6中引入)不可用,请使用默认的外观。
*详情请参阅http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
*/
试一试{
for(javax.swing.UIManager.LookAndFeelInfo:javax.swing.UIManager.getInstalledLookAndFeels()){
if(“Nimbus”.equals(info.getName())){
setLookAndFeel(info.getClassName());
打破
}
}
}捕获(ClassNotFoundException ex){
getLogger(RecentItemList.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}catch(实例化异常){
getLogger(RecentItemList.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}捕获(非法访问例外){
java.util.logging.Logger.getLogger(RecentItemList.class.getN
public class RecentItem extends javax.swing.JFrame {

    JTextArea tx;
    int i=0;
    int recentItems_count=0;
    String filename;
    String recentItem;
    Queue<String> q;
    public RecentItem() {
        q=new LinkedList<>();
        initComponents();
    }


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

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

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jMenu1.setText("File");



        open.setText("Open");
        open.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openActionPerformed(evt);
            }
        });
        jMenu1.add(open);

        recentItems.setText("Recent Items.....");
//        recentItems.addActionListener(new java.awt.event.ActionListener() {
//            public void actionPerformed(java.awt.event.ActionEvent evt) {
//                recentItemsActionPerformed(evt);
//            }
//        }); /* NO NEED FOR THESE */
        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 openActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openActionPerformed

           FileDialog fd = new FileDialog(RecentItem.this, "Select File", FileDialog.LOAD);
           fd.show();
           String title;
           String sts;
           if (fd.getFile() != null) {
           sts = fd.getDirectory() + fd.getFile();
           title=fd.getFile();
           //System.out.println("title :"+sts);
           BufferedReader br = null;
           StringBuffer str = new StringBuffer("");
           try {
                br = new BufferedReader(new FileReader(sts));
                String line;
                try {
                    while ((line = br.readLine()) != null) {
                        str.append(line + "\n");
                    }
                } catch (IOException ex) {
                    Logger.getLogger(RecentItem.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(RecentItem.class.getName()).log(Level.SEVERE, null, ex);
            }
            String t = str.toString();
            final JInternalFrame internalFrame = new JInternalFrame("",true,true);  
            tx = new JTextArea();
            internalFrame.add(tx);
            i+=1;
            internalFrame.setName("Document"+i);
            internalFrame.setTitle(title);
            tp.add(internalFrame);
            internalFrame.setVisible(true);
            internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
                @Override
                public void internalFrameClosing(InternalFrameEvent e) {
                    tp.remove(internalFrame);
                }
            });
            tx.setText(t);
            q.add(sts);
            /*CHANGES*/
            JMenuItem STS=new JMenuItem(sts); //creating new menu item with the string
            STS.addActionListener(new java.awt.event.ActionListener() {  //adding action listenner
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    subMenuActionPerformed(evt,sts);
                }               
            });
            recentItems.add(STS);  //adding the newly created item to the menu

            recentItems_count++;

            if(recentItems_count>2){
                recentItem=(String)q.remove();
                recentItems.removeAll();
                // recentItems_count--;
                for (String string : q) {
                     /*DOING THE SAME, HERE AGAIN */
                    JMenuItem item=new JMenuItem(string);
                    item.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                            subMenuActionPerformed(evt,string);
                        }               
                    });
                    recentItems.add(item);
                }
            }
            try {
                br.close();
            } catch (IOException ex) {
                Logger.getLogger(RecentItem.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /*EVENT TO OPEN A FILE IN NEW TAB*/
    private void subMenuActionPerformed(ActionEvent evt, String title) {
        BufferedReader br = null;
           StringBuffer str = new StringBuffer("");
           String fileName=new File(title).getName();
             try {
                br = new BufferedReader(new FileReader(title));
                String line;
             try {
                        while ((line = br.readLine()) != null) {
                        str.append(line + "\n");
                    }
                    } catch (IOException ex) {
                    Logger.getLogger(RecentItem.class.getName()).log(Level.SEVERE, null, ex);
                }
                } catch (FileNotFoundException ex) {
                Logger.getLogger(RecentItem.class.getName()).log(Level.SEVERE, null, ex);
            }
         String t = str.toString();
         final JInternalFrame internalFrame = new JInternalFrame("",true,true);  
        tx = new JTextArea();
        internalFrame.add(tx);
        i+=1;
        internalFrame.setName("Document"+i);
        internalFrame.setTitle(fileName);
        tp.add(internalFrame);
        internalFrame.setVisible(true);
             internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
        @Override
        public void internalFrameClosing(InternalFrameEvent e) {
            tp.remove(internalFrame);
        }
    });
            tx.setText(t);
            try{
            br.close();
        } catch(IOException e){}

               }

//    private void recentItemsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_recentItemsActionPerformed
//        Object[] selectedObjects = recentItems.getSelectedObjects();
//        System.out.println(selectedObjects);
//
//    }//GEN-LAST:event_recentItemsActionPerformed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        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(RecentItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(RecentItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(RecentItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RecentItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new RecentItem().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem create;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem open;
    private javax.swing.JMenu recentItems;
    private javax.swing.JMenuItem save;
    private javax.swing.JTabbedPane tp;
    // End of variables declaration//GEN-END:variables

}
        JMenuItem STS=new JMenuItem(sts); //creating new menu item with the string
        STS.addActionListener(new java.awt.event.ActionListener() {  //adding action listenner
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                subMenuActionPerformed(evt,sts);
            }               
        });
        recentItems.add(STS);  //adding the newly created item to the menu

        recentItems_count++;

        if(recentItems_count>2){
            recentItem=(String)q.remove();
            recentItems.removeAll();
            // recentItems_count--;
            for (String string : q) {
                 /*DOING THE SAME, HERE AGAIN */
                JMenuItem item=new JMenuItem(string);
                item.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(java.awt.event.ActionEvent evt) {
                        subMenuActionPerformed(evt,string);
                    }               
                });
                recentItems.add(item);
            }
        }
private void subMenuActionPerformed(ActionEvent evt, String title) {
    BufferedReader br = null;
       StringBuffer str = new StringBuffer("");
       String fileName=new File(title).getName();
         try {
            br = new BufferedReader(new FileReader(title));
            String line;
         try {
                    while ((line = br.readLine()) != null) {
                    str.append(line + "\n");
                }
                } catch (IOException ex) {
                Logger.getLogger(RecentItem.class.getName()).log(Level.SEVERE, null, ex);
            }
            } catch (FileNotFoundException ex) {
            Logger.getLogger(RecentItem.class.getName()).log(Level.SEVERE, null, ex);
        }
     String t = str.toString();
     final JInternalFrame internalFrame = new JInternalFrame("",true,true);  
    tx = new JTextArea();
    internalFrame.add(tx);
    i+=1;
    internalFrame.setName("Document"+i);
    internalFrame.setTitle(fileName);
    tp.add(internalFrame);
    internalFrame.setVisible(true);
         internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
    @Override
    public void internalFrameClosing(InternalFrameEvent e) {
        tp.remove(internalFrame);
    }
});
        tx.setText(t);

        try{
            br.close();
        } catch(IOException e){}

           }