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);
// 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();
}
}
आउटपुट
