-1

I've seen the question answered in How do I create a right click context menu in Java Swing? and seen how I can create a menu. However, when I associate it with the text area, it doesn't matter if it has anything written on it or not, it always shows the menu.

I use the text area to reveal how many objects I have created from a specific class (which I save in a ArrayList). What I need, is a menu that when clicking on a specific line of text, it can have the index of the object in the ArrayList and use that menu to Edit/Remove that specified object from the ArrayList. Is that possible with a Text Area or should I use a different type of displaying component?

As an Example:

Text Area:

Object 1.

Object 2.

Object 3.

When I select , for example, Object 1 with a right click, it shows the menu with Edit and Remove. But when I dont select any of them, the menu does not show. And when it Shows, it can access the index od the object (object 1 -> index 0, object 2 -> index 1 , etc.)

Thanks a lot for your help, Nhekas

Community
  • 1
  • 1
dgteixeira
  • 61
  • 9
  • It's not hard to do. Try it and if you get a problem, then ask us. – Sergiy Medvynskyy May 12 '16 at 11:57
  • I did try, and what I cannot do is join the location I get from the mouse (MouseEvent.getPoint()) and which line it corresponds in the JTextArea, mostly because, since it is inside a scrollPane, when I scroll down, the getPoint() won't change if I click on the same location. – dgteixeira May 12 '16 at 14:05
  • Look at JScrollPane's getViewPosition method. – FredK May 12 '16 at 14:34

1 Answers1

1

I use the text area to reveal how many objects I have created from a specific class

Don't use a JTextArea.

Instead I would suggest you should be using a JList. Read the section from the Swing tutorial on How to Use Lists for more information and examples.

The JList has a locationToIndex(...) method which will give you the row where the mouse was clicked. Then you can get the object from the list.

camickr
  • 321,443
  • 19
  • 166
  • 288