Search code examples
javaswingjscrollpanelayout-managergrouplayout

Cannot add JScrollPane to JTextArea in GroupLayout


Here is the code for what I tried but the scroll pane is not showing up and am using Group-layout.

import java.awt.BorderLayout;

public class JScrollPanel extends JFrame {

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                JScrollPanel frame = new JScrollPanel();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public JScrollPanel() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);

    **final JTextArea textArea = new JTextArea();

    JScrollPane scrollpanedreapta = new JScrollPane(textArea, 
        JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
           JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    contentPane.add(scrollpanedreapta, null);**

    GroupLayout gl_contentPane = new GroupLayout(contentPane);
    gl_contentPane.setHorizontalGroup(
        gl_contentPane.createParallelGroup(Alignment.LEADING)
            .addGroup(gl_contentPane.createSequentialGroup()
                .addGap(31)
                .addComponent(textArea, GroupLayout.PREFERRED_SIZE, 339, GroupLayout.PREFERRED_SIZE)
                .addContainerGap(54, Short.MAX_VALUE))
    );
    gl_contentPane.setVerticalGroup(
        gl_contentPane.createParallelGroup(Alignment.LEADING)
            .addGroup(gl_contentPane.createSequentialGroup()
                .addGap(31)
                .addComponent(textArea, GroupLayout.PREFERRED_SIZE, 172, GroupLayout.PREFERRED_SIZE)
                .addContainerGap(49, Short.MAX_VALUE))
    );
    contentPane.setLayout(gl_contentPane);
}
}

When I launch the code, it works fine and when I overflow the Text-area, both scroll-panes are not showing up. Any Help Guys.


Solution

  • You should add the JScrollPane to your layout groups instead of JTextArea, i.e. replace

    .addComponent(textArea, ...)
    

    with

    .addComponent(scrollpanedreapta, ...)
    

    two times.