When i open file first time file is opened but if

2019-09-15 18:27发布

问题:

Firstly open file through open menuitem but when second time open i choose the same file it opened in new tab. my requirement it not opened in new tab and display the message file already exist.

Here is my code,

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:

You can maintain a ArrayList of AbsoluteFilepath , and remove them from list when internalframe is closed . I have updated your code.Please check and reply

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
}