When i open file first time file is opened but if choose the second time same file not opened how to do it in java swing?

只谈情不闲聊 提交于 2020-01-17 04:35:10

问题


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
}


来源:https://stackoverflow.com/questions/26054325/when-i-open-file-first-time-file-is-opened-but-if-choose-the-second-time-same-fi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!