DethRaid
DethRaid

Reputation: 75

Enter key not working in JTextArea

I'm working on a Java Swing application. I have a JTextArea inside a JScrollPane inside a JTabbedPane inside a JPanel. I can type in the JTextArea, and every key on my keyboard has the desired effect, except the enter key.

Tabs and spaces work fine. When I press the enter key, then type to the end of the line with word wrap enabled, the line is broken where I typed the enter key, leading me to believe that the issue is with how the JTextArea is displaying the text. I'm giving the JTextArea a new HTMLDocument. Note that when I do not give the JTextArea a new HTMLDocument, the enter key works perfectly well.

Simple code reproducing the problem:

import javax.swing.*;
import javax.swing.text.html.HTMLDocument;
import java.awt.*;

public class Driver extends JFrame {
    public Driver() {
        setLayout( new GridLayout( 1, 1 ) );

        JTabbedPane tabbedPane = new JTabbedPane();
        add( tabbedPane );

        JTextArea textArea = new JTextArea( new HTMLDocument() );
        textArea.setLineWrap( true );

        JScrollPane scrollPane = new JScrollPane( textArea );
        tabbedPane.addTab( "No enter key!", scrollPane );

        pack();
        getContentPane().setVisible( true );
        setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
        setSize( 640, 480 );
        setVisible( true );
        setFocusable( true );
    }

    public static void main( String[] args ) {
        new Driver();
    }
}

Upvotes: 2

Views: 508

Answers (1)

rghome
rghome

Reputation: 8819

JTextArea doesn't understand HTMLDocument - it is not intended for styled documents. You will have to use JTextPane with an HTMLEditorKit so it knows it is HTML. For some reason, you can't supply your own document, but if you get the one from the component it works OK.

    final HTMLEditorKit htmlKit = new HTMLEditorKit();
    final JTextPane textPane = new JTextPane( );
    textPane.setEditorKit(htmlKit);
    textPane.setEditable(true);
    JScrollPane scrollPane = new JScrollPane( textPane );

    Document doc = textPane.getDocument();
    System.out.println(doc.getClass().getName()); // It's an HTML Document

Upvotes: 2

Related Questions