-1

I'm having difficulty in getting resources that will help me with an issue. I want to add a button that will let me insert text anywhere in my JFrame so I can click and add a text

Before that, I have been using JTextField and JTextArea, but these are useful in a predefined space (I believe).

What I want is like the classic Add Text button in Paint ("A" button) in which when you click on it, you will have the text cursor (like an "I") and then click somewhere in the frame so I can actually add text in that area. Which I call "adding text dynamically". Unfortunately I don't have any code to show because I'm not sure how to build the code from scratch or maybe use a method in Swing, but I'm more than keen to explain better if this is too generic for you guys.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
danielrvo
  • 1
  • 4
  • Should the user have the opportunity to move or remove the text after it is added? – Andrew Thompson Oct 10 '19 at 05:40
  • *and then click somewhere in the frame so I can actually add text in that area.* - Check out: https://stackoverflow.com/questions/25411278/java-graphics2d-text-field/25412439#25412439. It shows how you can double click and add text to a panel in a random location. – camickr Oct 10 '19 at 14:00

1 Answers1

1

You're going to need to be familiar with Java graphics and associated methods, particularly drawString(), so start by reading the official Graphics Tutorial.

Then learn about MouseListeners, which will help you recognize when and where the user clicks in your JFrame.

Then learn about KeyListeners, which will allow you to detect when your user is typing. You may wish to use a key bind instead, but as described, your UI is relatively simple with only one focusable component, so keylisteners are probably OK.

This general strategy should help you take a flying leap at the problem:

  1. detect mouseclick with mouselistener

  2. draw an insertion bar

  3. detect keypress with keylistener

  4. use graphics.drawstring to draw the character specified by the keypress

  5. redraw the insertion bar

Make sure your keylistener handles the enter key, so that you know when to erase the insertion bar. You're going to paint your JFrame in between each of those steps.

The result will be crude, to say the least, and you'll notice that you have to handle a lot of issues that crop up along the way before things start to look professional. For example, you'll have to deal with font metrics. Not every character is going to be the same width, so you have to calculate the X argument to your drawString() based on the charWidth of whatever character the user types. You might do well to start with a monospaced font for that reason.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
MarsAtomic
  • 10,436
  • 5
  • 35
  • 56