//my program response to left mouse button click, drag with left mouse button will not show the effect you want
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class myFrame extends JFrame
{
final int JT_COL = 50;
final int JT_ROW = 40;
Highlighter hilite;
int myCount;
JTextArea JT;
public myFrame()
{
getContentPane().setLayout(new BorderLayout());
JT = new JTextArea("oneone\ntwoone\nthree",JT_ROW,JT_COL);
MouseListener myMouse = new MouseListener()
{
public void mouseClicked(MouseEvent e)
{
mySelect(JT.getCaretPosition(),JT);
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e)
{}
};
JT.addMouseListener(myMouse);
JScrollPane scroller = new JScrollPane();
scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JViewport vp = scroller.getViewport();
vp.add(JT);
getContentPane().add(scroller, BorderLayout.CENTER);
}
public void mySelect(int pos,JTextArea tempJT)
{
int possibleCaretPos[][] = new int[JT_ROW][2];
int found=0;
StringBuffer sb = new StringBuffer(tempJT.getText());
int totalLen = (tempJT.getText()).length();
Color myColor;
myColor = new Color(204,204,255);
hilite = JT.getHighlighter();
hilite.removeAllHighlights();
int row=0;
if (totalLen>0)
{
possibleCaretPos[0][0]=0;
for (int i=0; i<totalLen; i++)
if (sb.charAt(i)=='\n')
{
possibleCaretPos[row][1]=i;
row++;
possibleCaretPos[row][0]=i+1;
}
possibleCaretPos[row][1]=totalLen;
for (int m=row; m>=0; m--)
{
if (pos>=possibleCaretPos[m][0])
{
found = m;
break;
}
}
}
try
{
myCount++;
//System.out.println(pos+"addhigh"+myCount+" s"+startPos+" e"+endPos);
hilite.addHighlight(possibleCaretPos[found][0], possibleCaretPos[found][1], new DefaultHighlighter.DefaultHighlightPainter (myColor));
}
catch (BadLocationException e) {}
}
public static void main(String args[]) {
myFrame myframeObj = new myFrame();
myframeObj.setSize(800, 300);
myframeObj.setVisible(true);
myframeObj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {
public MyHighlightPainter(Color color) {
super(color);
}
}