Search code examples
javaswingjoptionpanejdialogjinternalframe

Using java swing I opened a text file into jtextarea, after closing it JoptionPanedialog box always appear


I loaded a text file into jtextarea then modified its content but when I close it jinternalframe closes but always shows the dialog box even if I don't modify the text. And this is my problem, because I want the dialog box to appear only if the text is modified.

How can I test this condition?

Here is my code:

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

    // <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 ) {
    filename=file.getPath();
        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(Exception e)

        {

        }
        String t = str.toString();
        final JInternalFrame internalFrame = new JInternalFrame("",true,true); 
        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);
        }           
        tx.setText(t);
        internalFrame.add(tx);
        tp.add(internalFrame);
        try{
            tp.setSelectedIndex(i-1);  
        }
        catch(IndexOutOfBoundsException ioe){   
        }
     internalFrame.setTitle(filename);
        tp.add(internalFrame);
        try {
            tp.setSelectedIndex(i-1);  
        }
        catch(IndexOutOfBoundsException ioe){      
        }
        internalFrame.setVisible(true);
        internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
            @Override
            public void internalFrameClosing(InternalFrameEvent e) {
                String name=tx.getName();

      if(tx.getText().length()>0){
        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);

        }
      }

            }
        });   

    }

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

Is there any suggestion?


Solution

  • You should use the document listener instead of if...else. Use a boolean variable to check whether file is modified or not if that file is modified the open then dialog box otherwise close the frame.

    UPDATE To clarify the code I've updated the code please check the updated code

    boolean updated = false;       //instance variable
    
        public Class_name()            //would be your constructor or you can put code in initializing method
        {
    
            TextArea tx = new TextArea();
            Document doc = tx.getDocument();
            doc.addDocumentListener(this);
    
            internalFrame.addWindowListener(new WindowAdapter()
            {
                  public void windowClosing(WindowEvent e)
                  {
                        if(updated)
                        {
                            //show dialog box and save changes
                            internalFrame.dispose();
                        }
                        else
                            internalFrame.dispose();
                  }
            });
        }   
            after that add use this code in overridden methods
            public void insertUpdate(DocumentEvent e)
            {
                 updated = true;
            }
            public void removeUpdate(DocumentEvent e)
            {
                 updated = true;
            }
            public void changeUpdate(DocumentEvent e)
            {
                 updated = true;
            }