使用JTextPane转到特定的行号

时间:2014-06-12 09:24:54

标签: 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                   
}

2 个答案:

答案 0 :(得分:1)

查看Text Utilities中的gotoStartOfLine(...)方法,了解更有效的解决方案,该解决方案利用文本组件使用的Element Document结构。

答案 1 :(得分:0)

我添加了一个新方法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  
}