Search code examples
javaswingjpaneljscrollpanejtextarea

JTextArea width stretches with input even when using setLineWrap(true) & setWrapStyleWord(true)


When the frame appears the JTextArea stetches horizontally until it reaches the frame width size and on resize of the frame the JTextArea will stretch again to match the width of the frame. If input is added the JTextArea it will continue to grow horizontally rather than wrapping the text on to a new line.

Without the setLineWrap(true) and setWrapStyleWord(true) the JTextArea will be presented on the frame correctly but still stretch the JTextArea on the first line.

How can I fix this issue?

public class GridBagExample {

private JFrame frame;
private final JPanel panel;
private JLabel frontText, reverseText;
private JTextField frontTextField;
private final JTextArea reverseTextArea;
private GridBagLayout gridBagLayout;
private GridBagConstraints constraints;
private JButton submit, cancel;

public GridBagExample() {

    frame = new JFrame("Create new flashcard");
    gridBagLayout = new GridBagLayout();
    constraints = new GridBagConstraints();
    panel = new JPanel(gridBagLayout);
    panel.setSize(240,220);

    frontText = new JLabel("Front Text");
    constraints.ipadx = 1;
    constraints.ipady = 1;
    constraints.gridx = 0;
    constraints.gridy = 0;
    gridBagLayout.setConstraints(frontText, constraints);
    panel.add(frontText);

    frontTextField = new JTextField(15);
    constraints.ipadx = 1;
    constraints.ipady = 1;
    constraints.gridx = 2;
    constraints.gridy = 0;
    gridBagLayout.setConstraints(frontTextField, constraints);
    panel.add(frontTextField);

    reverseText = new JLabel("Reverse Text");
    constraints.ipadx = 1;
    constraints.ipady = 1;
    constraints.gridx = 0;
    constraints.gridy = 1;
    gridBagLayout.setConstraints(reverseText, constraints);
    panel.add(reverseText);

    reverseTextArea = new JTextArea(5,15);
    reverseTextArea.setWrapStyleWord(true);
    reverseTextArea.setLineWrap(true);
    constraints.ipadx = 1;
    constraints.ipady = 1;
    constraints.gridx = 2;
    constraints.gridy = 1;
    gridBagLayout.setConstraints(reverseTextArea, constraints);
    panel.add(reverseTextArea);


    submit = new JButton("Submit");
    constraints.ipadx = 1;
    constraints.ipady = 1;
    constraints.gridx = 2;
    constraints.gridy = 2;
    gridBagLayout.setConstraints(submit, constraints);
    panel.add(submit);

    frame.add(panel);
    frame.setSize(300, 300);
    frame.setVisible(true);
}

public static void main(String[] args) throws Exception {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new GridBagExample();
        }
    });
}
}

Solution

  • Don't add the text area to the panel directly. Put it inside a JScrollPane, and add the scroll pane to the panel, as explained in the tutorial.