-1

I have a JLabel and I want to get the text at a specific location using a mouselistener, so I want to get the word at a point on a jLabel.

I'm unsure if I'm able to use something else rather than a jLabel because I need html-compatibility and other conditions.

I tried to use a jTextArea once but I guess it didn't work as needed (I didn't work on the project for a while). Can anyone help me?

Lulu Keks
  • 1
  • 3

1 Answers1

1

I don't think you can do that with JLabel, but it is possible with a JTextComponent (such as JTextArea), thanks to the viewToModel() method, which:

Converts the given place in the view coordinate system to the nearest representative location in the model.

So, inside you MouseListener:

public void mouseClicked(MouseEvent e) {
   int index = textArea.viewToModel(new Point(e.getX(), e.getY()));
   String text = textArea.getText();
   String word = "";
   int i = index;
   while(isWordChar(text.charAt(i))) // Get text after the index
      word += text.charAt(i++);
   i = index-1;
   while(isWordChar(text.charAt(i))) // Get text before the index
      word = text.charAt(i--) + word;
}
Eric Leibenguth
  • 4,167
  • 3
  • 24
  • 51
  • Well that doesn't work :( **isWordChar** is an unknown method and even if it works like that how am I able to change the colors of specific lines if html doesn't work with jTextAreas? – Lulu Keks May 28 '15 at 19:40
  • OK. `isWordChart` is a function you have to write to check if a character is a letter or a whitespace. I just gave you a general direction here. Indeed `JTextArea` is not compatible with *rendering* html. For that you need a `JTextPane`, which works in a similar way, but with many more options. – Eric Leibenguth May 28 '15 at 19:50