Search code examples
javaswingjtextarea

JTextArea issue when writing. No limit texts go down the JFrame


There is a problem with my JTextArea. When I write, it goes down the frame and I don't know how to limit it so no more lines below the JFrame

Photo: describing my problem


Solution

  • After much research I have found a solution! I've discovered that making a JTextArea scrollable is based on the design of the program. This link is what helped me to get my JTextPane to work and is what I will be using as a reference. This is not the only way to do this, but if you have any questions, don't hesitate to ask! Thanks.


    As stated by others, you need to wrap your JTextArea in JScrollPane

    public class ScrollableJTextArea
    {
        JTextArea jTextArea     = new JTextArea();
    
        // Wrap JTextArea in a JScrollPane
        JScrollPane jScrollPane = new JScrollPane(jTextArea);
        ...
    

    Define a constructor for your GUI

    ScrollableJTextArea()
    {
        jTextArea.setLineWrap(true); // wrap text horizontally
        jScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane.setPreferredSize(new Dimension(380,350));
        // and so on...
    }
    

    And your main method

    public static void main(String[] args)
    {
        ScrollableJTextArea sjta = new ScrollableJTextArea();
        JFrame frame             = new JFrame();
        JPanel center            = new JPanel();
    
        // I've read on many forums as well as heard from many fellow classmates 
        // that it's better to add content to a panel rather than the frame itself
        frame.add(center, BorderLayout.CENTER);
        center.add(sjta.jScrollPane);
    
        frame.setSize(400, 400);
        frame.setVisible(true);
    }