Перейти к указанному номеру строки с помощью JTextPane

Я хочу поместить курсор на заданный пользователем номер строки. Для этого мне нужно было написать код. Но когда я ввожу строку номер 2, курсор помещается после первого символа, а не в начале второй строки. Пожалуйста, помогите мне... Спасибо. Вот код:

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                   
}

person user3709795    schedule 12.06.2014    source источник
comment
представление модели возвращает эти координаты   -  person mKorbel    schedule 12.06.2014
comment
@mKorbel Ответь, ответь, ответь!   -  person MadProgrammer    schedule 12.06.2014


Ответы (2)


Ознакомьтесь с методом gotoStartOfLine(...) в текстовых утилитах, чтобы найти более эффективное решение, которое использует структуру Element структуры Document, используемой текстовым компонентом.

person camickr    schedule 12.06.2014

Я добавил новый метод public int setcursor(int newlineno) и изменил ваш код. В этом методе я просто вычисляю ожидаемую позицию курсора.

Запустите приведенный ниже код;)

import java.awt.Rectangle;
import java.util.Scanner;

import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;

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() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createActionPerformed(evt);
            }
        });
        file.add(create);
        goTo.setText("GoTo");
        goTo.addActionListener(new java.awt.event.ActionListener() {
            @Override
            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();
                System.out.println(lineCount);
                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 ) {
                //Rectangle rectangle = textPane.modelToView(textPane.getCaretPosition());
                textPane.setCaretPosition(0);
                System.out.println(setcursor(lineNumber));
                textPane.setCaretPosition(setcursor(lineNumber));
                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 int setcursor(int newlineno) {
        int pos = 0;
        int i = 0;
        String line = "";
        Scanner sc = new Scanner(textPane.getText());
        while (sc.hasNextLine()) {
            line = sc.nextLine();
            i++;
            if (newlineno > i) {
                pos = pos + line.length() + 1;
            }
        }
        return pos;
    }

    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  
}
person Arijit    schedule 12.06.2014
comment
@ user3709795, не самое эффективное решение, поскольку оно не использует преимущества структуры элемента документа. Сначала метод getText() должен выполнить итерацию по структуре элемента документа, чтобы создать строку. Затем вам нужно разобрать строку и разбить ее на отдельные строки текста. Становится менее эффективным по мере добавления новых строк в документ. - person camickr; 12.06.2014
comment
@camickr Я знаю, что мое решение не очень эффективно, но я никогда не использовал предложенные вами текстовые утилиты. Хорошая вещь, чтобы учиться. :) +1 к вашему ответу за его показ. - person Arijit; 13.06.2014