Search code examples
javaswingjscrollpanelayout-managernull-layout-manager

adding ScrollBar to JTextArea


I want to add a scroll bar into my text area and I know the simple code for adding scroll bar but when I put the code for scroll bar the whole text area disappears!

What is the problem?

Here is my code:

private JFrame frame;
private JTextArea textarea;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {

                SmsForm window = new SmsForm();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public SmsForm() {
    initialize();
}

private void initialize() {
    frame = new JFrame("???");
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
    JPanel groupBoxEncryption = new JPanel();

    final JTextArea textarea=new JTextArea();
    textarea.setBounds(50, 100, 300, 100);
    frame.getContentPane().add(textarea);
    textarea.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

    JScrollPane scrollPanePlain = new JScrollPane(textarea);
    groupBoxEncryption.add(scrollPanePlain);
    scrollPanePlain.setBounds(100, 30, 250, 100);
    scrollPanePlain.setVisible(true);

Solution

  • There are a number of issues

    • You need to add the JPanel groupBoxEncryption to the application JFrame
    • Don't add the textarea to the frame - components can only have one parent component
    • As already mentioned, you're using null layout which doesnt size components - forget about not a layout manager.
    • As JPanel uses FlowLayout by default, you need to override getPreferredSize for the panel groupBoxEncryption. Better yet use a layout manager such as GridLayout that automatically sizes the component

    Example

    JPanel groupBoxEncryption = new JPanel(new GridLayout());