Java:光标当前位置的列号和行号

发布于 2024-10-19 16:10:04 字数 84 浏览 3 评论 0原文

我想知道JTextArea中光标所在的列号和行号。 IE。在记事本中,当我在第一行时,状态栏显示 Ln 1,Col 1。

提前感谢...

I want to know the column number and row number where the cursor in JTextArea.
ie. in notepad when i m at first line than status bar shows Ln 1, Col 1.

thanks in advance...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

π浅易 2024-10-26 16:10:04

这里是代码

import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.event.*;

public class caretDemo extends JFrame {
    // Two controls, one is the editor and the other is our little status bar at the bottom.
    // When we update the editor, the change in caret will update the status text field.
    private JTextArea editor;
    private JTextField status;

    // Start of our caretDemo class
    public caretDemo() {
        setTitle("Caret Demo");
        setSize(500,500);

        // Lets create a border layout to make positioning of items easy and quick.
        setLayout(new BorderLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        editor = new JTextArea();

        // Add a caretListener to the editor. This is an anonymous class because it is inline and has no specific name.
        editor.addCaretListener(new CaretListener() {
            // Each time the caret is moved, it will trigger the listener and its method caretUpdate.
            // It will then pass the event to the update method including the source of the event (which is our textarea control)
            public void caretUpdate(CaretEvent e) {
                JTextArea editArea = (JTextArea)e.getSource();

                // Lets start with some default values for the line and column.
                int linenum = 1;
                int columnnum = 1;

                // We create a try catch to catch any exceptions. We will simply ignore such an error for our demonstration.
                try {
                    // First we find the position of the caret. This is the number of where the caret is in relation to the start of the JTextArea
                    // in the upper left corner. We use this position to find offset values (eg what line we are on for the given position as well as
                    // what position that line starts on.
                    int caretpos = editArea.getCaretPosition();
                    linenum = editArea.getLineOfOffset(caretpos);

                    // We subtract the offset of where our line starts from the overall caret position.
                    // So lets say that we are on line 5 and that line starts at caret position 100, if our caret position is currently 106
                    // we know that we must be on column 6 of line 5.
                    columnnum = caretpos - editArea.getLineStartOffset(linenum);

                    // We have to add one here because line numbers start at 0 for getLineOfOffset and we want it to start at 1 for display.
                    linenum += 1;
                }
                catch(Exception ex) { }

                // Once we know the position of the line and the column, pass it to a helper function for updating the status bar.
                updateStatus(linenum, columnnum);
            }
        });

        // Add the fields to the layout, the editor in the middle and the status at the bottom.
        add(editor, BorderLayout.CENTER);

        status = new JTextField();
        add(status, BorderLayout.SOUTH);

        // Give the status update value
        updateStatus(1,1);
    }

    // This helper function updates the status bar with the line number and column number.
    private void updateStatus(int linenumber, int columnnumber) {
        status.setText("Line: " + linenumber + " Column: " + columnnumber);
    }

    // Entry point to the program. It kicks off by creating an instance of our class and making it visible.
    public static void main(String args[]) {
        caretDemo caretDemoApp = new caretDemo();
        caretDemoApp.setVisible(true);
    }
}

输出

在此处输入图像描述

Here is the code

import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.event.*;

public class caretDemo extends JFrame {
    // Two controls, one is the editor and the other is our little status bar at the bottom.
    // When we update the editor, the change in caret will update the status text field.
    private JTextArea editor;
    private JTextField status;

    // Start of our caretDemo class
    public caretDemo() {
        setTitle("Caret Demo");
        setSize(500,500);

        // Lets create a border layout to make positioning of items easy and quick.
        setLayout(new BorderLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        editor = new JTextArea();

        // Add a caretListener to the editor. This is an anonymous class because it is inline and has no specific name.
        editor.addCaretListener(new CaretListener() {
            // Each time the caret is moved, it will trigger the listener and its method caretUpdate.
            // It will then pass the event to the update method including the source of the event (which is our textarea control)
            public void caretUpdate(CaretEvent e) {
                JTextArea editArea = (JTextArea)e.getSource();

                // Lets start with some default values for the line and column.
                int linenum = 1;
                int columnnum = 1;

                // We create a try catch to catch any exceptions. We will simply ignore such an error for our demonstration.
                try {
                    // First we find the position of the caret. This is the number of where the caret is in relation to the start of the JTextArea
                    // in the upper left corner. We use this position to find offset values (eg what line we are on for the given position as well as
                    // what position that line starts on.
                    int caretpos = editArea.getCaretPosition();
                    linenum = editArea.getLineOfOffset(caretpos);

                    // We subtract the offset of where our line starts from the overall caret position.
                    // So lets say that we are on line 5 and that line starts at caret position 100, if our caret position is currently 106
                    // we know that we must be on column 6 of line 5.
                    columnnum = caretpos - editArea.getLineStartOffset(linenum);

                    // We have to add one here because line numbers start at 0 for getLineOfOffset and we want it to start at 1 for display.
                    linenum += 1;
                }
                catch(Exception ex) { }

                // Once we know the position of the line and the column, pass it to a helper function for updating the status bar.
                updateStatus(linenum, columnnum);
            }
        });

        // Add the fields to the layout, the editor in the middle and the status at the bottom.
        add(editor, BorderLayout.CENTER);

        status = new JTextField();
        add(status, BorderLayout.SOUTH);

        // Give the status update value
        updateStatus(1,1);
    }

    // This helper function updates the status bar with the line number and column number.
    private void updateStatus(int linenumber, int columnnumber) {
        status.setText("Line: " + linenumber + " Column: " + columnnumber);
    }

    // Entry point to the program. It kicks off by creating an instance of our class and making it visible.
    public static void main(String args[]) {
        caretDemo caretDemoApp = new caretDemo();
        caretDemoApp.setVisible(true);
    }
}

Output

enter image description here

浅忆流年 2024-10-26 16:10:04

您需要使用 Utilities.getRowStart 以及插入符号位置如下所示:

获取行号:

int caretPos = textArea.getCaretPosition();
int rowNum = (caretPos == 0) ? 1 : 0;
for (int offset = caretPos; offset > 0;) {
    offset = Utilities.getRowStart(textArea, offset) - 1;
    rowNum++;
}
System.out.println("Row: " + rowNum);    

获取列号:

int offset = Utilities.getRowStart(textArea, caretPos);
int colNum = caretPos - offset + 1;
System.out.println("Col: " + colNum);

You need to use Utilities.getRowStart along with the caret position as shown below:

To get the row number:

int caretPos = textArea.getCaretPosition();
int rowNum = (caretPos == 0) ? 1 : 0;
for (int offset = caretPos; offset > 0;) {
    offset = Utilities.getRowStart(textArea, offset) - 1;
    rowNum++;
}
System.out.println("Row: " + rowNum);    

To get the column number:

int offset = Utilities.getRowStart(textArea, caretPos);
int colNum = caretPos - offset + 1;
System.out.println("Col: " + colNum);
拥抱我好吗 2024-10-26 16:10:04

您是否尝试过 getCaretPosition

您必须计算 \n 才能知道您有哪一行,并且必须计算当前插入符位置与最后一次出现 \n 字符之间的差异。

Have you tried getCaretPosition?

You have to count \n to know which line you have, and you have to count the difference between current caret position and last occurrence of \n character.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文