如何在 Java 中 JTextArea 内显示行号?


JTextArea JTextComponent 的子类,它是一个多行文本组件,用于显示文本或允许用户输入文本。JTextArea 可以生成一个CaretListener 接口,该接口可以监听插入符更新事件。默认情况下,JTextArea 不显示行号,我们必须使用DocumentListener 接口来自定义代码。

示例

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.Element;
public class LineNumberTextAreaTest extends JFrame {
   private static JTextArea textArea;
   private static JTextArea lines;
   private JScrollPane jsp;
   public LineNumberTextAreaTest() {
      setTitle("LineNumberTextArea Test");
      jsp = new JScrollPane();
      textArea = new JTextArea();
      lines = new JTextArea("1");
      lines.setBackground(Color.LIGHT_GRAY);
      lines.setEditable(false);
      //  Code to implement line numbers inside the JTextArea
      textArea.getDocument().addDocumentListener(new DocumentListener() {
         public String getText() {
            int caretPosition = textArea.getDocument().getLength();
            Element root = textArea.getDocument().getDefaultRootElement();
            String text = "1" + System.getProperty("line.separator");
               for(int i = 2; i < root.getElementIndex(caretPosition) + 2; i++) {
                  text += i + System.getProperty("line.separator");
               }
            return text;
         }
         @Override
         public void changedUpdate(DocumentEvent de) {
            lines.setText(getText());
         }
         @Override
         public void insertUpdate(DocumentEvent de) {
            lines.setText(getText());
         }
         @Override
         public void removeUpdate(DocumentEvent de) {
            lines.setText(getText());
         }
      });
      jsp.getViewport().add(textArea);
      jsp.setRowHeaderView(lines);
      add(jsp);
      setSize(400, 275);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new LineNumberTextAreaTest();
   }
}

输出

更新时间: 2020-02-10

833 次查看

开启你的 职业生涯

完成课程即可获得认证

立即开始
广告
© . All rights reserved.