Search code examples
javaswingawtdocumentjtextpane

How to work functionality for all Documents in swing


I want work functionality for all opened Documents not current open Document only. I had created one swing application. I was open an Document. The cut, copy, paste and selectAll operations through menuItem work for currently opened documents; not working for the previous opened Documents. Please help me.

Here is my code:

public class OpenDemo extends javax.swing.JFrame implements ChangeListener{
JTextPane textPane;
JTextPane lnNum;
JScrollPane scrollPane;
int i=0;
JTextField status;
ArrayList<JTextPane> textPanes=new ArrayList<>();
public OpenDemo() {
    initComponents();
    viewLineNumbers.setSelected(false);
}
@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();
    cut = new javax.swing.JMenuItem();
    selectAll = new javax.swing.JMenuItem();
    viewLineNumbers = new javax.swing.JCheckBoxMenuItem();

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

    cut.setText("Cut");
    cut.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cutActionPerformed(evt);
        }
    });
    jMenu1.add(cut);

    selectAll.setText("SelectAll");
    selectAll.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            selectAllActionPerformed(evt);
        }
    });
    jMenu1.add(selectAll);

    viewLineNumbers.setSelected(true);
    viewLineNumbers.setText("ViewLineNumbers");
    viewLineNumbers.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            viewLineNumbersActionPerformed(evt);
        }
    });
    jMenu1.add(viewLineNumbers);

    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.DEFAULT_SIZE, 279, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        
private void updateStatus(int linenumber, int columnnumber) {
status.setText("Line: " + linenumber + " Column: " + columnnumber);
}    
private void openActionPerformed(java.awt.event.ActionEvent evt) {                                     
    FileDialog fd = new FileDialog(OpenDemo.this, "Select File", FileDialog.LOAD);
    fd.show();
    String title;
    String sts;
    File f;
    if (fd.getFile() != null) {
       sts = fd.getDirectory() + fd.getFile();
       title=fd.getFile();
       System.out.println(sts);
       title=fd.getFile();
       BufferedReader br = null;
       StringBuffer str = new StringBuffer("");
       try {
           br = new BufferedReader(new FileReader(sts));
           String line;
           try {
                while ((line = br.readLine()) != null) {
                str.append(line + "\n");
                }
           } catch (IOException ex) {
                Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
             }
       } catch (FileNotFoundException ex) {
            Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
         }
       String t = str.toString(); 
       final JInternalFrame internalFrame = new JInternalFrame("",true,true);  
       textPane = new JTextPane();
       textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
       internalFrame.add(textPane);
       i++;
       internalFrame.setName("Doc "+i);
       internalFrame.setTitle(title);
       try {
            internalFrame.setSelected(true);
        } catch (PropertyVetoException ex) {
            Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
       }
       textPane.addCaretListener(new CaretListener() {
        @Override
       public void caretUpdate(CaretEvent e) {
          JTextPane editArea = (JTextPane)e.getSource();
          int linenum = 1;
          int columnnum = 1;
           try {
                int caretpos = editArea.getCaretPosition();
                linenum=getLineAtCaret(editArea)-1;
                columnnum=getColumnAtCaret(editArea);
                linenum += 1;
            }
            catch(Exception ex) { }
            updateStatus(linenum, columnnum);
        }
    });
       status=new JTextField();
       status.setBackground(Color.LIGHT_GRAY);
       internalFrame.add(status,BorderLayout.SOUTH);
       tp.add(internalFrame);
       scrollPane=new JScrollPane(textPane);
       tp.setSelectedIndex(i-1);  
       internalFrame.add(scrollPane);
       internalFrame.setVisible(true);   
       textPane.setText(t);
       tp.addChangeListener(this);
       textPanes.add(textPane);
       textPane.setCaretPosition(0);
}     
}                                    

private void cutActionPerformed(java.awt.event.ActionEvent evt) {                                    
    textPane.cut();
}                                   

private void selectAllActionPerformed(java.awt.event.ActionEvent evt) {                                          
    textPane.selectAll();
}                                         

private void viewLineNumbersActionPerformed(java.awt.event.ActionEvent evt) {                                                
    AbstractButton button = (AbstractButton) evt.getSource();
                  if(button.isSelected()){
                    lnNum = new JTextPane();
                    lnNum.setEditable(false);
                    lnNum.setSize(50,50);
                    lnNum.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
                    lnNum.setText(getText());
                    textPane.getDocument().addDocumentListener(new DocumentListener(){
                      @Override
                      public void changedUpdate(DocumentEvent de) {
                      lnNum.setText(getText());
                    }
                   @Override
                   public void insertUpdate(DocumentEvent de) {
                    lnNum.setText(getText());
                   }
                   @Override
                   public void removeUpdate(DocumentEvent de) {
                    lnNum.setText(getText());
                   }
                  });
                   scrollPane.getViewport().add(textPane);
                   scrollPane.setRowHeaderView(lnNum); 
                   }
                   else{
                       scrollPane.setRowHeaderView(null);
                   }           
}                                               
public String getText(){
    int caretPosition = textPane.getDocument().getLength();
    javax.swing.text.Element root = textPane.getDocument().getDefaultRootElement();
    String text = "1" + System.getProperty("line.separator");
    for(int i = 2; i <=  root.getElementIndex( caretPosition ) + 1; i++){
        text += i + System.getProperty("line.separator");
    }
    return text;
 }
public static void main(String args[]) {
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new OpenDemo().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JMenuItem cut;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JMenuItem selectAll;
private javax.swing.JTabbedPane tp;
private javax.swing.JCheckBoxMenuItem viewLineNumbers;
// End of variables declaration                   

@Override
public void stateChanged(ChangeEvent ce) {
    JTabbedPane sourceTabbedPane = (JTabbedPane) ce.getSource();
    int index = sourceTabbedPane.getSelectedIndex();
    try
    {
      textPane =textPanes.get(index);
    }
    catch(IndexOutOfBoundsException e1){
    }
}
public int getLineAtCaret(JTextComponent component)
{
    int caretPosition = component.getCaretPosition();
    Element root = component.getDocument().getDefaultRootElement();
    return root.getElementIndex( caretPosition ) + 1;
}
public int getColumnAtCaret(JTextComponent component)
{
    FontMetrics fm = component.getFontMetrics( component.getFont() );
    int characterWidth = fm.stringWidth( "0" );
    int column = 0;
    try
    {
        Rectangle r = component.modelToView( component.getCaretPosition() );
        int width = r.x - component.getInsets().left;
        column = width / characterWidth;
    }
    catch(BadLocationException ble) {}
    return column + 1;
}

}


Solution

  • I think, i managed to answer all your problems, but i needed to create another class which i called 'OInternalFrame', so i will give you both code for those class. Tell me if that's what you were trying to achieve :

    OpenDemo :

        import java.awt.FileDialog;
    import java.awt.FontMetrics;
    import java.awt.Rectangle;
    import java.beans.PropertyVetoException;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    import javax.swing.AbstractButton;
    import javax.swing.JTabbedPane;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import javax.swing.event.InternalFrameAdapter;
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Element;
    import javax.swing.text.JTextComponent;
    
    public class OpenDemo extends javax.swing.JFrame implements ChangeListener{
    
    
    
    private ArrayList<OInternalFrame> frames = new ArrayList<OInternalFrame>();
    private OInternalFrame currentFrame;
    int i=0;
    public OpenDemo() {
        initComponents();
        viewLineNumbers.setSelected(false);
    }
    @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();
        cut = new javax.swing.JMenuItem();
        selectAll = new javax.swing.JMenuItem();
        viewLineNumbers = new javax.swing.JCheckBoxMenuItem();
    
        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);
    
        cut.setText("Cut");
        cut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cutActionPerformed(evt);
            }
        });
        jMenu1.add(cut);
    
        selectAll.setText("SelectAll");
        selectAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectAllActionPerformed(evt);
            }
        });
        jMenu1.add(selectAll);
    
        viewLineNumbers.setSelected(true);
        viewLineNumbers.setText("ViewLineNumbers");
        viewLineNumbers.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewLineNumbersActionPerformed(evt);
            }
        });
        jMenu1.add(viewLineNumbers);
    
        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.DEFAULT_SIZE, 279, Short.MAX_VALUE)
        );
    
        pack();
    }// </editor-fold>                        
    
    private void openActionPerformed(java.awt.event.ActionEvent evt) {                                     
        FileDialog fd = new FileDialog(OpenDemo.this, "Select File", FileDialog.LOAD);
        fd.show();
        String title;
        String sts;
    
        if (fd.getFile() != null) {
           sts = fd.getDirectory() + fd.getFile();
           title=fd.getFile();
           System.out.println(sts);
           title=fd.getFile();
           BufferedReader br = null;
           StringBuffer str = new StringBuffer("");
           try {
               br = new BufferedReader(new FileReader(sts));
               String line;
               try {
                    while ((line = br.readLine()) != null) {
                    str.append(line + "\n");
                    }
               } catch (IOException ex) {
                    Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
                 }
           } catch (FileNotFoundException ex) {
                Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
             }
           String t = str.toString(); 
           OInternalFrame internalFrame = new OInternalFrame("",true,true);  
    
    
           i++;
           internalFrame.setName("Doc "+i);
           internalFrame.setTitle(title);
           try {
                internalFrame.setSelected(true);
            } catch (PropertyVetoException ex) {
                Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
           }
    
    
           internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
               @Override
               public void internalFrameClosing(InternalFrameEvent e) {
                   i--;
    
                   frames.remove(currentFrame);
                   tp.remove(currentFrame);
                   for(OInternalFrame frame : frames)
                  {
                      int index=frames.indexOf(frame);
    
                      tp.setTitleAt(index, "Doc "+(index+1));
    
                  }
    
               }
           });
           tp.add(internalFrame);
           tp.setSelectedIndex(i-1);  
    
    
    
           tp.addChangeListener(this);
           frames.add(internalFrame);
           currentFrame=internalFrame;
           currentFrame.setText(t);
           currentFrame.setVisible(true);
           currentFrame.setLineViewer(viewLineNumbers.isSelected());
    
    }     
    }                                    
    
    private void cutActionPerformed(java.awt.event.ActionEvent evt) {                                    
        currentFrame.cut();
    }                                   
    
    private void selectAllActionPerformed(java.awt.event.ActionEvent evt) {                                          
        currentFrame.selectAll();
    }                                         
    
    private void viewLineNumbersActionPerformed(java.awt.event.ActionEvent evt) {                                                
        AbstractButton button = (AbstractButton) evt.getSource();
    
                          currentFrame.setLineViewer(viewLineNumbers.isSelected());
    
    }                                               
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new OpenDemo().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify                     
    private javax.swing.JMenuItem cut;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem open;
    private javax.swing.JMenuItem selectAll;
    private javax.swing.JTabbedPane tp;
    private javax.swing.JCheckBoxMenuItem viewLineNumbers;
    // End of variables declaration                   
    
    @Override
    public void stateChanged(ChangeEvent ce) {
        JTabbedPane sourceTabbedPane = (JTabbedPane) ce.getSource();
        int index = sourceTabbedPane.getSelectedIndex();
        try
        {
          currentFrame =frames.get(index);
          currentFrame.setLineViewer(viewLineNumbers.isSelected());
        }
        catch(IndexOutOfBoundsException e1){
        }
    }
    public int getLineAtCaret(JTextComponent component)
    {
        int caretPosition = component.getCaretPosition();
        Element root = component.getDocument().getDefaultRootElement();
        return root.getElementIndex( caretPosition ) + 1;
    }
    public int getColumnAtCaret(JTextComponent component)
    {
        FontMetrics fm = component.getFontMetrics( component.getFont() );
        int characterWidth = fm.stringWidth( "0" );
        int column = 0;
        try
        {
            Rectangle r = component.modelToView( component.getCaretPosition() );
            int width = r.x - component.getInsets().left;
            column = width / characterWidth;
        }
        catch(BadLocationException ble) {}
        return column + 1;
    }
    }
    

    OInternalFrame :

        import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.FontMetrics;
    import java.awt.Rectangle;
    
    import javax.swing.JInternalFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.JTextPane;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Element;
    import javax.swing.text.JTextComponent;
    
    
    public class OInternalFrame extends JInternalFrame
    {
        private JTextArea textPane;
        private JScrollPane scrollPane;
        private JTextPane linePane;
        private JTextField status;
        private DocumentListener listen;
        public OInternalFrame(String title,boolean resizable,boolean closable)
        {
            super(title,resizable,closable);
            initComponents();
            initListeners();
        }
        private void initComponents()
        {
    
            textPane = new JTextArea();
            linePane = new JTextPane();
            status = new JTextField();
            scrollPane = new JScrollPane();
            textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
            status.setBackground(Color.LIGHT_GRAY);
    
            linePane.setEditable(false);
            linePane.setSize(50,50);
            linePane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
            status.setEditable(false);
    //        add(textPane);
    
            add(scrollPane);
    
            add(status,BorderLayout.SOUTH);
            scrollPane.getViewport().add(textPane);
            scrollPane.setRowHeaderView(linePane); 
            setVisible(true);
            linePane.setVisible(false);
            updateStatus(1,1);
            scrollPane.setVisible(true);
    
        }
        private void initListeners()
        {
            textPane.addCaretListener(new CaretListener() {
                @Override
                public void caretUpdate(CaretEvent e) {
    
                    int linenum = 1;
                    int columnnum = 1;
                    try {
                        int caretpos = textPane.getCaretPosition();
                        linenum=getLineAtCaret()-1;
                        columnnum=getColumnAtCaret();
                        linenum += 1;
                    }
                    catch(Exception ex) { }
                    updateStatus(linenum, columnnum);
                }
            });
            listen = new DocumentListener(){
                @Override
                public void changedUpdate(DocumentEvent de) {
                linePane.setText(getText());
              }
             @Override
             public void insertUpdate(DocumentEvent de) {
              linePane.setText(getText());
             }
             @Override
             public void removeUpdate(DocumentEvent de) {
              linePane.setText(getText());
             }
            };
    
    
             }
    
        public int getLineAtCaret()
        {   
            int line = 0;
            int caretPosition = textPane.getCaretPosition();
    
    
            try {
                line = textPane.getLineOfOffset(caretPosition);
    
            } catch (BadLocationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return line+1;
        }
    
        public int getColumnAtCaret()
        {
            FontMetrics fm = textPane.getFontMetrics( textPane.getFont() );
            int characterWidth = fm.stringWidth( "0" );
            int column = 0;
            try
            {
                Rectangle r = textPane.modelToView( textPane.getCaretPosition() );
                int width = r.x - textPane.getInsets().left;
                column = width / characterWidth;
            }
            catch(BadLocationException ble) {}
            return column + 1;
        }
    
        private void updateStatus(int linenumber, int columnnumber) 
        {
            status.setText("Line: " + linenumber + " Column: " + columnnumber);
        }    
    
    
        public void setText(String t)
        {
            System.out.println(t);
    
            textPane.setText(t);
    
            textPane.setCaretPosition(0);
            textPane.setVisible(true);
            textPane.repaint();
        }
        public void setLineViewer(boolean enabled)
        {
            if(enabled)
            {
            linePane.setText(getText());
            linePane.setCaretPosition(0);
            linePane.revalidate();
            linePane.repaint();
    
            textPane.getDocument().addDocumentListener(listen);
            }
            else
            {
                linePane.setText("");
                textPane.getDocument().removeDocumentListener(listen);
            }
    
    
            linePane.setVisible(enabled);
        }
        public void cut()
        {
            textPane.cut();
        }
        public void selectAll()
        {
            textPane.selectAll();
        }
        public String getText(){
            int caretPosition = textPane.getLineCount();
    
            String text = "1" + System.getProperty("line.separator");
            for(int i = 2; i <=  caretPosition-1; i++){
                text += i + System.getProperty("line.separator");
            }
            return text;
         }
    }