当我打开文件第一次打开文件但如果第二次选择同一个文件未打开怎么办java swing?

时间:2014-09-26 07:33:11

标签: java swing jtabbedpane fileopendialog

首先通过打开的menuitem打开文件,但第二次打开时,我选择在新标签页中打开的同一文件。我的要求它没有在新标签中打开并显示消息文件已经存在。

这是我的代码,

public class Open extends javax.swing.JFrame {
JTextArea tx;
int i=0;
public Open() {
initComponents();
}


@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();
    Open = new javax.swing.JMenuItem();

    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);

    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) {                                     
    final JFileChooser jc = new JFileChooser();
        JComponent panel = new JPanel((LayoutManager) new FlowLayout(
            FlowLayout.LEFT));

    int returnVal=  jc.showOpenDialog(Open.this);
  String title;
    String sts;
   File file=null;
 if(returnVal == JFileChooser.APPROVE_OPTION)     
 file = jc.getSelectedFile();    
 JTextArea text = new JTextArea();
 if (jc.getSelectedFile()!= null) {
  tx = new JTextArea();
    BufferedReader br = null;
    StringBuffer str = new StringBuffer("");
     StringBuffer st = new StringBuffer("");
      try {
        br = new BufferedReader(new FileReader(file));
        String line;

                 while ((line = br.readLine()) != null) {
                str.append(line + "\n");
            }
        } 
        catch (IOException ex) {
                Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
        }


    String t = str.toString();

    // tx = new JTextArea();

    final JInternalFrame internalFrame = new JInternalFrame("",true,true);  
  title=file.getName();
  sts=file.getPath();

    tx.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
    //tx.setLineWrap(true);
    internalFrame.add(tx);
    i+=1;
    internalFrame.setName("Doc "+i);
    JScrollPane  scrollpane=new JScrollPane(tx);

             internalFrame.setTitle(title);
    tp.add(internalFrame);
    try{
      tp.setSelectedIndex(i-1);  
    }
    catch(IndexOutOfBoundsException ioe){      
    }
     internalFrame.add(scrollpane);
    internalFrame.setVisible(true);
    internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
        @Override
        public void internalFrameClosing(InternalFrameEvent e) {
            tp.remove(internalFrame);
        }
    });   


    tx.setText(t);
   try {
            br.close();
            } 

         catch (IOException ex) {
            Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
        }
    }        
  }                                    
    public static void main(String args[]) {

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
               try {
                UIManager.setLookAndFeel(
                           UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnsupportedLookAndFeelException ex) {
                Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
            }
            new Open().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JMenuItem Open;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tp;
// End of variables declaration                   
 }

1 个答案:

答案 0 :(得分:0)

您可以维护AbsoluteFilepath的ArrayList,并在关闭internalframe时将其从列表中删除。我已更新您的代码。请检查并回复

import javax.swing.*;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Open extends javax.swing.JFrame {
JTextArea tx;
ArrayList<String> fileList;
int i=0;
public Open() {
    fileList=new ArrayList<String>();
    initComponents();
}


@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();
    Open = new javax.swing.JMenuItem();

    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);

    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) {
    final JFileChooser jc = new JFileChooser();
    JComponent panel = new JPanel((LayoutManager) new FlowLayout(
            FlowLayout.LEFT));

    int returnVal=  jc.showOpenDialog(Open.this);
    String title;
    String sts;
    File file=null;
    if(returnVal == JFileChooser.APPROVE_OPTION)
    file = jc.getSelectedFile();
    JTextArea text = new JTextArea();
    if (jc.getSelectedFile()!= null && !fileList.contains(file.getAbsolutePath())) {
        fileList.add(file.getAbsolutePath());
        tx = new JTextArea();
        BufferedReader br = null;
        StringBuffer str = new StringBuffer("");
        StringBuffer st = new StringBuffer("");
        try {
            br = new BufferedReader(new FileReader(file));
            String line;

            while ((line = br.readLine()) != null) {
                str.append(line + "\n");
            }
        }
        catch (IOException ex) {
            Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
        }


        String t = str.toString();

        // tx = new JTextArea();

        final JInternalFrame internalFrame = new JInternalFrame("",true,true);
        title=file.getName();
        sts=file.getPath();
        final String filePath=file.getAbsolutePath();
        tx.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
        //tx.setLineWrap(true);
        internalFrame.add(tx);
        i+=1;
        internalFrame.setName("Doc "+i);
        JScrollPane  scrollpane=new JScrollPane(tx);

        internalFrame.setTitle(title);
        tp.add(internalFrame);
        try{
            tp.setSelectedIndex(i-1);
        }
        catch(IndexOutOfBoundsException ioe){
        }
        internalFrame.add(scrollpane);
        internalFrame.setVisible(true);
        internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
            @Override
            public void internalFrameClosing(InternalFrameEvent e) {
                fileList.remove(filePath);
                tp.remove(internalFrame);
            }
        });


        tx.setText(t);
        try {
            br.close();
        }

        catch (IOException ex) {
            Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    else
    {
        JOptionPane.showMessageDialog(this, "File is already open");
    }
}
public static void main(String args[]) {

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                UIManager.setLookAndFeel(
                        UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnsupportedLookAndFeelException ex) {
                Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
            }
            new Open().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JMenuItem Open;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tp;
// End of variables declaration
}