2

I need some kind of JTextField that replace carriage return characters by a styled block displaying the text <New Line> with another font, style or color.

By example, the text..

Dear Mr. Smith,\nblablabla...\nRegards...

..would be shown to the user, in a one line JTextField, this way :

Dear Mr. Smith,<New Line>blablabla...<New Line>Regards...

These <New Line> should be blocks that are selectable as if it was a single character and could be deleted with a single backspace. Pressing the return key would add a <New Line> at the caret position.

I think it can be possible by overriding PlainDocument, but I'm stuck in difficult to understand Document and EditorKit APIs. I would need some pointers about this one...

I do not have any objection using a JTextPane or JEditorPane as long as it behaves like a JTextField (one line, no scroll-bars).

Any suggestions?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Béatrice Cassistat
  • 1,048
  • 12
  • 37

1 Answers1

5

Any suggestions ?

Use a JTextArea (a multi-line component) instead.

For an example, see this answer:


It would be simpler, but this is not what I have to do...

Fair enough, I missed the part that stated:

..with another font, style or color.

That would require a styled document such as JEditorPane or JTextPane.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Yes Andrew, it needs to be presented that way. I do not have any objection using a JTextPane or JEditorPane as long as it behave like a JTextField (one line, no scrollbars). – Béatrice Cassistat May 31 '12 at 02:19
  • Interesting trick @trashgod, maybe by replacing carriage returns by this unicode character, and convert them back, it may provide an acceptable workaround. – Béatrice Cassistat May 31 '12 at 02:22
  • I edited part of your comment back into the question. I am not sure if @trashgod would be notified of the comment without the `@`. – Andrew Thompson May 31 '12 at 02:25
  • To have different `Font, Style or Colour` for each `String Literal`, you are bound to look towards `JEditorPane/JTextPane`. THough how you want the `newline` to be displayed, it's the area of logic, You want to know that as an answer, or you already found one ? – nIcE cOw May 31 '12 at 02:37
  • @AndrewThompson: For reference, I saw your ping, but not that of François Cassistat; I'm not sure [why](http://meta.stackexchange.com/q/43019/163188). Please don't hesitate to cite my example in the `JTextArea` part of the answer. – trashgod May 31 '12 at 02:37
  • 1
    @trashgod I'm surprised I missed that opportunity (now rectified) to throw a good screenshot into the answer. :P – Andrew Thompson May 31 '12 at 02:48
  • @trashgod ..and where did get those ***shoes?*** (with apologies to Johnny from 'Airport'/'Flying High') One of the few occasions when two frames actually makes sense - though they would typically be on different screens. ;) – Andrew Thompson May 31 '12 at 03:02