Search code examples
javaswinglayoutgridbaglayout

GridBagLayout not showing JTextArea, and showing panel in center


In the following code, when I add the JTextArea to the main panel, it doesn't show up. When I add the controlPanel, it shows up in the center, not the edge. I'm new with GridBagLayout, so I'm assuming I'm missing something simple.

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextArea;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        JFrame frame = new JFrame();

        JPanel mainPanel = new JPanel();
        JPanel controlPanel = new JPanel();

        mainPanel.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        controlPanel.add(new JButton("Play"));
        controlPanel.add(new JButton("Pause"));
        controlPanel.add(new JSpinner());
        JTextArea textArea = new JTextArea();

        c.gridx = 0;
        c.gridy = 0;
        c.gridheight = 3;
        c.gridwidth = 3;
        mainPanel.add(textArea, c);
        // mainPanel.add(controlPanel, c);
        frame.add(mainPanel);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(700, 700);
        frame.setLocation(250, 100);
        frame.setVisible(true);
    }
}

EDIT: This is how the constraints look after your suggestions. The textArea still does not show up.

        c.gridx = 0;
        c.gridy = 0;
//      c.gridheight = 3;
//      c.gridwidth = 3;
        c.weightx = 1.0;
        c.weighty = 1.0;
        c.anchor = GridBagConstraints.NORTHWEST;
        mainPanel.add(textArea, c);
        // mainPanel.add(controlPanel, c);
        frame.add(mainPanel);

Solution

  • Don't forget weights and anchors:

        c.weightx = 1.0;
        c.weighty = 1.0;
        c.anchor = GridBagConstraints.NORTHWEST;
    

    Edit:
    Example of adding row and column values to the JTextArea:

        controlPanel.add(new JButton("Play"));
        controlPanel.add(new JButton("Pause"));
        controlPanel.add(new JSpinner());
    
        JTextArea textArea = new JTextArea(20, 40);
    
        c.gridx = 0;
        c.gridy = 0;
        c.gridheight = 3;
        c.gridwidth = 3;
        c.weightx = 1.0;
        c.weighty = 1.0;
        c.anchor = GridBagConstraints.NORTHWEST;
        mainPanel.add(new JScrollPane(textArea), c);