Hi,
I have pasted below the code
for getting the line number of the text
in a JTextArea added to a JScrollPane.
Hope this serves your purpose.
Best Wishes,
premila
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class LineCount extends javax.swing.JFrame {
JTextArea ta=new JTextArea();
JScrollPane spane=new JScrollPane();
public LineCount() {
initComponents();
this.getContentPane().setLayout(null);
spane.setBounds(20,20,200,100);
ta.setLineWrap(true);
ta.setEditable(false);
String s="I've a JTextArea with 20 rows. In that JTextArea I've more than 20 rows of text. I'd place the JTextArea in a JScrollPane so that I can scroll the area.Now I want to know when I'm click with my mouse in the area which row I hit (the real row-number of that text, mean that the number can be higher than 20).Is it possible to get it? ";
ta.setText(s);
ta.addMouseListener(new MouseListen());
spane.getViewport().add(ta);
spane.setAutoscrolls(true);
this.getContentPane().add(spane);
}
private void initComponents() {//GEN-BEGIN:initComponents
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
pack();
}//GEN-END:initComponents
private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
System.exit(0);
}//GEN-LAST:event_exitForm
public static void main(String args[]) {
LineCount lc=new LineCount();
lc.setSize(300,300);
lc.show();
}
class MouseListen implements MouseListener {
public void mouseExited(java.awt.event.MouseEvent mouseEvent) {
}
public void mouseReleased(java.awt.event.MouseEvent mouseEvent) {
}
public void mousePressed(java.awt.event.MouseEvent mouseEvent) {
}
public void mouseClicked(java.awt.event.MouseEvent me) {
int x=me.getX();
int y=me.getY();
int pos=ta.viewToModel(new java.awt.Point(x,y));
Font f=ta.getFont();
FontMetrics fm=ta.getFontMetrics(f);
int height=fm.getHeight();
System.out.println("Current LineNumber is "+( (y/height)+1 ));
}
public void mouseEntered(java.awt.event.MouseEvent mouseEvent) {
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}