java - 使用 JTextPane GoTo 指定行号

标签 java swing awt 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                   
}

最佳答案

查看 Text Utilities 中的 gotoStartOfLine(...) 方法以获得更有效的解决方案,利用文本组件使用的 DocumentElement 结构。

关于java - 使用 JTextPane GoTo 指定行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24180839/

相关文章:

java - 如何调整jws小程序窗口的大小?

java - 如何对包含图标的 JTable 列进行排序?

java - 使用 DAO 模式的优缺点

dd-MMM-yyyy 格式的 java.time.format.DateTimeParseException

java - 使用自定义 TableCellRenderer 的 Swing JTable

java - Mac 上不显示图形

java - 当我运行作业时,springBatch 中的 ItemReadListener 未运行

java - 如何解决使用GluonHQ客户端、Native Image和GraalVM编译的JavaFX项目中的fxml加载异常?

java - JScrollPane 不会单独出现

java - ActionListener 不起作用