How to work documentlistener with jtabbedpane?

狂风中的少年 提交于 2019-12-12 01:47:22

问题


Open Two files By using Jtabbedpane.Document listener work each file independently.If you modify one file document listener enabled only for particular file. How to do this?. When open two files

Here is my code,

import java.beans.PropertyVetoException;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
 import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.text.Document;

public class Close extends javax.swing.JFrame {
JTextArea tx;

File file;
String filename=null;
int i=0;
boolean update =false;
public Close() {
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();
int returnVal=  jc.showOpenDialog(Close.this);
String title;
String s=null;
if(returnVal == JFileChooser.APPROVE_OPTION)     
file = jc.getSelectedFile();
if (jc.getSelectedFile()!= null) {
   BufferedReader br = null;
    StringBuffer str = new StringBuffer("");
    StringBuffer str1 = new StringBuffer("");
    StringBuilder st = new StringBuilder("");
    StringBuilder sbHex = new StringBuilder();
    StringBuilder sbText = new StringBuilder();
    StringBuilder sbResult = new StringBuilder();
    final StringBuilder pb = new StringBuilder();
    int bytesCounter =0;        
    String helloWorldInHex=null;
    int value=0;
    try {
        br = new BufferedReader(new FileReader(file));
        String line;
        try {

                while ((line = br.readLine()) != null) {
                str.append(line + "\n");
            }
        } 
        catch (IOException ex) {
            Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 
    catch (FileNotFoundException ex) {
        Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
    }
    String t = str.toString();
   filename=file.getPath();
   final JInternalFrame internalFrame = new JInternalFrame("",true,true); 
  final String filePath=file.getAbsolutePath();
  i++;
  internalFrame.setName("Doc "+i);
   tx=new JTextArea();
     internalFrame.setTitle(filename);
    try {
        internalFrame.setSelected(true);
    } 
    catch (PropertyVetoException ex) {
        Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
    }           
    tp.add(internalFrame);
    try{
        tp.setSelectedIndex(i-1);  
    }
    catch(IndexOutOfBoundsException ioe){   
    }
    tx.setText(t);
    internalFrame.add(tx);
  internalFrame.setVisible(true);

  Document doc=tx.getDocument();
  doc.addDocumentListener(new DocumentListener() {
       @Override
       public void insertUpdate(DocumentEvent e) {
        update =true;
       }

       @Override
       public void removeUpdate(DocumentEvent e) {
           update =true;
       }

       @Override
       public void changedUpdate(DocumentEvent e) {
           update =true;
       }
   });
    internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
        @Override
        public void internalFrameClosing(InternalFrameEvent e) {


            String name=tx.getName();

 if(update==true){

      update=false;
    int reply = JOptionPane.showConfirmDialog(null,
                                      "Save Changes to this Document", "Quit", JOptionPane.YES_NO_CANCEL_OPTION);
        int chooserStatus;
    if (reply == JOptionPane.YES_OPTION){
      boolean success;
            String editorString;
            FileWriter fwriter;
            PrintWriter outputFile;
            try {
                DataOutputStream d = new DataOutputStream(new FileOutputStream(filename));
                String line = tx.getText();
                BufferedReader br = new BufferedReader(new StringReader(line));
                while((line = br.readLine())!=null) {
                    d.writeBytes(line + "\r\n");
                }
            }
            catch (IOException ee) {       
                success = false;
            }
     success = true;
            i--;
           tp.remove(internalFrame);
       }
    else if(reply==JOptionPane.NO_OPTION)
    {
        i--;
  tp.remove(internalFrame);
   }
  }
 else 
 {
      i--;
tp.remove(internalFrame);
 }

        }
    });   

   }

   }                                    
  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                   
  }

Thank you.


回答1:


  public class Open extends javax.swing.JFrame {
  JTextArea tx;
  ArrayList<String> fileList;
  File file;
  Map<Integer,String> m;
  Map<String,Boolean> m1;
  String filename=null;
   int i=0;
  int j=-1;
  boolean update =false;
  boolean changed=false;
public Open() {

   fileList=new ArrayList<String>();
   m=new HashMap<Integer,String>();
      m1=new HashMap<String, Boolean>();
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();
   int returnVal=  jc.showOpenDialog(Open.this);
    String title;
    String s=null;
    if(returnVal == JFileChooser.APPROVE_OPTION)     
    file = jc.getSelectedFile();
      if (jc.getSelectedFile()!= null) {
       BufferedReader br = null;
        StringBuffer str = new StringBuffer("");
        StringBuffer str1 = new StringBuffer("");
        StringBuilder st = new StringBuilder("");
        StringBuilder sbHex = new StringBuilder();
        StringBuilder sbText = new StringBuilder();
        StringBuilder sbResult = new StringBuilder();
        final StringBuilder pb = new StringBuilder();
        int bytesCounter =0;        
        String helloWorldInHex=null;
        int value=0;
        try {
            br = new BufferedReader(new FileReader(file));
            String line;
            try {

                    while ((line = br.readLine()) != null) {
                    str.append(line + "\n");
                }
            } 
            catch (IOException ex) {
                Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
            }
        } 
        catch (FileNotFoundException ex) {
            Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
        }
        String t = str.toString();
       filename=file.getPath();
       final JInternalFrame internalFrame = new JInternalFrame("",true,true); 
      final String filePath=file.getAbsolutePath();
      i++;
      internalFrame.setName("Doc "+i);
       tx=new JTextArea();
         internalFrame.setTitle(filename);
        try {
            internalFrame.setSelected(true);
        } 
        catch (PropertyVetoException ex) {
            Logger.getLogger(Open.class.getName()).log(Level.SEVERE, null, ex);
        }           
        tp.add(internalFrame);
        try{
            tp.setSelectedIndex(i-1);  
        }
        catch(IndexOutOfBoundsException ioe){   
        }
        tx.setText(t);
        internalFrame.add(tx);
      internalFrame.setVisible(true);
     final Document doc=tx.getDocument();

           doc.addDocumentListener(new DocumentListener() {
           @Override
           public void insertUpdate(DocumentEvent e) {
               System.out.println("insert");


             Component c = tp.getSelectedComponent();
        if( c instanceof JInternalFrame)
        {
            JInternalFrame f = (JInternalFrame)c;
            if(!fileList.contains(f.getTitle()))
            {


                fileList.add(f.getTitle());
                 update =true;
            }
        }

           }

           @Override
           public void removeUpdate(DocumentEvent e) {
               update =true;
           }

           @Override
           public void changedUpdate(DocumentEvent e) {
               update =true;
           }
       });    

        internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
            @Override
            public void internalFrameClosing(InternalFrameEvent e) {


                String name=tx.getName();

              Component c = tp.getSelectedComponent();
        if( c instanceof JInternalFrame)
        {
             JInternalFrame f = (JInternalFrame)c;

        String path=f.getTitle();


         if(fileList.contains(path)){
             fileList.remove(path);


          update=false;
        int reply = JOptionPane.showConfirmDialog(null,
                                          "Save Changes to this Document", "Quit", JOptionPane.YES_NO_CANCEL_OPTION);
           int chooserStatus;
        if (reply == JOptionPane.YES_OPTION){
          boolean success;
                String editorString;
                FileWriter fwriter;
                PrintWriter outputFile;
                try {
                     FileOutputStream fos = new FileOutputStream(filename);
                    DataOutputStream d = new DataOutputStream(fos);
                    System.out.println("conetent2            "+filename);

                    String line = tx.getText();
                   System.out.println("conetent            "+line);
                    BufferedReader br = new BufferedReader(new StringReader(line));
                    while((line = br.readLine())!=null) {
                        d.writeBytes(line + "\r\n");
                    }

                }
                catch (IOException ee) {     
                     System.out.println("conetent     qqw112222       ");
                    success = false;
                }

         success = true;
                i--;
               tp.remove(internalFrame);
           }
        else if(reply==JOptionPane.NO_OPTION)
        {
            i--;
      tp.remove(internalFrame);
       }
      }

     else 
     {

          i--;
    tp.remove(internalFrame);
     }
        }     
           }
        });   


    j++;



   }

  }                                    
  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/26646163/how-to-work-documentlistener-with-jtabbedpane

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