Search code examples
javaswingjscrollpanejtextarea

Is it possible to have non variable dimemsions in a JTextArea?


I want to put an sql statement in a JTextArea. Right now I have this:

sql = new JTextArea(7, 20);
JScrollPane scrollPane1 = new JScrollPane(sql);
sql.setEditable(false);
sql.setFont(new Font("Arial", Font.BOLD, 14));
scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

this.add(scrollPane1);

When I put the sql statement inside, the dimensions adjust to the content. In this case it makes the JTextArea as wide as the sql statement. What I want is that when it doesn't fit, it will split up and when this doesn't fit anymore, there will be a scrollpane. Does anyone have an idea of how to fix this? Thanks in advance!


Solution

  • You can use JTextArea#setLineWrap(true) by default is set to false.

    Sets the line-wrapping policy of the text area. If set to true the lines will be wrapped if they are too long to fit within the allocated width. If set to false, the lines will always be unwrapped. A PropertyChange event ("lineWrap") is fired when the policy is changed. By default this property is false.

    Also see this method JTextArea#setWrapStyleWord(true)