Home > Back-end >  JTextPane is not adding a new line when reading text from HTML file
JTextPane is not adding a new line when reading text from HTML file

Time:03-03

I am attempting to read text from an HTML file based on the id of the element and display it in a JTextPane. However, when I read in the text and display it, it is not going to a new line. Here is an example of the HTML being read in:

<!-- LOOK BED command text -->
<p id="look-bed">
    The bed looks hard and uncomfortable.<br>
</p>


<!-- LOOK FOOD command text -->
<p id="look-food">
    The food doesn't look very appetizing.<br>
</p>

The method that I am using to read from the HTML page is:

   public static String ReadFromHTMLFile(String tagId) {
        Document htmlFile;
        File file = new File("GameText.html");
        try {
            htmlFile = Jsoup.parse(file, "UTF-8");
            Element element = htmlFile.getElementById(tagId);
            return String.valueOf(element);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return "Unable to access "   tagId   " element";
    }

The method that I am using to update the text in the JTextPane is:

   public static void SetGameText(String location, String text, boolean appendText) {
        if(appendText) {
            try {
                HTMLDocument doc = (HTMLDocument) gameText.getStyledDocument();
                doc.insertAfterEnd(doc.getCharacterElement(doc.getLength()), text);
            }
            catch (IOException | BadLocationException e) {
                e.printStackTrace();
            }
        }
        else {
            gameText.setText("");
            gameText.setText(location   text);
        }
    }

The user is supposed to enter a command in a text box and click the submit button and get feedback based on the command that was entered. The problem is that each of the commands that are entered appear on the same line instead of a new line.

The part of the SetGameText method that runs if appendText is false functions the way it is supposed to, creating line breaks where I want them, but the part that runs if appendText is true is not creating a line break, even though I am using the <br> tag in the HTML.

CodePudding user response:

For a reasonable display of HTML documents use JEditorPane. Switch it to text/html content and you should be able to get your stuff rendered.

Also check how to make div to new line how to get DIVs on one line each.

When in doubt, simply add <br/> elements.

CodePudding user response:

I figured out what to do to solve the problem. Instead of putting the text in a

tag, I put it in a tag and set the display to block and it is working like I want it to.

For example I changed:

<p id="look-bed">
    The bed looks hard and uncomfortable.
</p>

to:

<div id="look-bed">
    The bed looks hard and uncomfortable.
</div>
  • Related