-1

How do I set the contents of a JTextPane to a String array? I'm making a memorization application that removes random words that a user enters in a JTextPane and replaces it with underscores. I want to convert what the user enters to a string array with each index being a separate word.

Does anybody have any ideas of how to accomplish this?

Any and all help is appreciated!

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Fouroh3
  • 542
  • 2
  • 10
  • 27
  • 1
    What do you have so far? – dic19 Oct 15 '13 at 21:31
  • Well I'm not really sure where to start. I have created the frame and blank classes. I was thinking that there may be a way to determine separate words because of spaces. – Fouroh3 Oct 15 '13 at 21:34
  • Yes certainly there is a way to do that. Take a look to this question: [How do I split a string with any whitespace chars as delimiters?](http://stackoverflow.com/questions/225337/how-do-i-split-a-string-with-any-whitespace-chars-as-delimiters) – dic19 Oct 15 '13 at 21:37

2 Answers2

4

Some tips:

  • Get the text from JTextArea or JTextPane through getText() method. It will return a String
  • Split the String by white spaces. Take a look to this answer: How do I split a string with any whitespace chars as delimiters?. You'll have a String[] as desired.
  • Do your random replacements.
  • Set text back to the JTextArea or JTextPane.
Community
  • 1
  • 1
dic19
  • 17,821
  • 6
  • 40
  • 69
1

You can use javax.swing.text.Utilities. It has 2 methods

public static final int getWordStart(JTextComponent c, int offs)
public static final int getWordEnd(JTextComponent c, int offs)

You can start from 0 offset and search for the next word end. Then start search next word start after the end of the first word etc.

The methods use locale dependent word break iterator.

BreakIterator.getWordInstance(c.getLocale())
StanislavL
  • 56,971
  • 9
  • 68
  • 98