Display a row of Strings on a JComponent so that the single Strings are selectable/their location getLocation()-able?
In order to be able to display a sentence on a, say, JPanel
with a GridLayout(1,0)
[i.e., only one line/row] and then be able to draw a syntax tree (or similar) above it, I want to display the sentence as a row of String
s, which each include one word.
The single String
s should then be either selectable (as in a JList
), or I should at least be able to get their Location on the JPanel
via getLocation()
.
Up to this point I have tried the following options, and had the following issues:
- Single String
s as JLabel
s: The JLabel
s are stretched out to fill the JPanel
width, re-sizing them to fit the single String
they're displaying seems complicated. I would want to be able to do this, however, to make the sentence look like a sentence and not like a badly layed out table.
- JList
: All the functionality I want, but I'm unaware of an option to re-size the "cells" of a single String
(cf. JLabel
above). Also, I'm having difficulties restricting display of 开发者_开发百科the JList to a single line/row (cf. another of my questions).
- JTextArea
: I couldn't get my head round how to get the Location of the single String
s that I had appended to the JTextArea
.
I'm aware that drawString()
might be an option, but I'm afraid to use it since I don't want to mix AWT and Swing. Also, I would need to calculate the int
values for x
and y
for every single String
. And I'm not sure whether I'd be able to get their Locations at all (although I could of course save their int
s in a Map or Vector since I have to calculate them anyway).
Thankful for any suggestions! Thanks!
I would use JTextArea
and method modelToView()/viewToModel()
to get x,y for position in nthe string and position in the string for coordinates x and y.
Also use Utilities
class getWordStart() getWordEnd() getRowStart() getRowEnd()
methods.
EDIT: As noted by camickr in the comments, setSize()
is not an appropriate way to lay out Components (as this is automatically done by the respective LayoutManager
, I have removed the respective code from my answer.
Triggered by StanislavL's answer, I have found a solution to do it via JTextField
, albeit by using one for each String
rather than just one (as suggested by StanislavL).
I can now easily getLocation()
for each JTextField
. Simple, really!
I'd like to thank StanislavL for his answer, without which I'd never have though about this, and camickr for his comment.
精彩评论