Search code examples
javaswingawtjtextpane

GoTo specified line number using JTextPane


I want to place the cursor to user given line number.For this I had write code.But,when I enter a line number 2 the cursor was placed in after first character not in start of the second line.Please help me...Thank you. Here is code:

public class GoToAction extends javax.swing.JFrame {

    int i=0;
    JTextPane textPane;
    int lineCount;

    public GoToAction() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        tabbedPane = new javax.swing.JTabbedPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        file = new javax.swing.JMenu();
        create = new javax.swing.JMenuItem();
        goTo = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        file.setText("File");

        create.setText("Create");
        create.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createActionPerformed(evt);
            }
        });
        file.add(create);

        goTo.setText("GoTo");
        goTo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                goToActionPerformed(evt);
            }
        });
        file.add(goTo);

        jMenuBar1.add(file);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    private void createActionPerformed(java.awt.event.ActionEvent evt) {                                       
        final JInternalFrame internalFrame = new JInternalFrame("");
        i++;
        internalFrame.setName("Document"+i);
        internalFrame.setClosable(true);
        internalFrame.setAutoscrolls(true);
        textPane=new JTextPane();
        textPane.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
        internalFrame.add(textPane);
        tabbedPane.add(internalFrame);
        internalFrame.setSize(internalFrame.getMaximumSize());
        internalFrame.pack();
        internalFrame.setVisible(true);
    }                                      

    private void goToActionPerformed(java.awt.event.ActionEvent evt) {                                     
           do {
          try {
          String str = (String)JOptionPane.showInputDialog(this,"Line number:\t","Goto line",JOptionPane.PLAIN_MESSAGE,null,null,null);
          if( str == null ) {
          break;
          }
          int lineNumber = Integer.parseInt(str);
          lineCount=getLineCount();
          if ( lineNumber > lineCount ) {
          JOptionPane.showMessageDialog(this,"Line number out of range","EPAD Goto line",JOptionPane.ERROR_MESSAGE);
          continue;
          }   
          for ( int i = 0 ; i < lineCount; i++ ){
          if ( i+1 == lineNumber ) {
              textPane.setCaretPosition(i);
                      return;
          }
          }
          } catch ( Exception e ) {
          }
         } while ( true );
    }                                    
    public int getLineCount(){ 
        lineCount=0;
        Scanner sc=new Scanner(textPane.getText());
        while(sc.hasNextLine()){
            String line = sc.nextLine(); 
            lineCount++;
       }
        return lineCount;
    }
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        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(GoToAction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GoToAction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GoToAction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GoToAction.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new GoToAction().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JMenuItem create;
    private javax.swing.JMenu file;
    private javax.swing.JMenuItem goTo;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JTabbedPane tabbedPane;
    // End of variables declaration                   
}

Solution

  • Check out the gotoStartOfLine(...) method in Text Utilities for a more efficient solution that takes advantage of the Element structure of the Document used by the text component.