Search code examples
javaswinguser-interfaceboxlayout

java gui boxlayout question


I am working on a java gui application hard coding without any netbeans help. I am using the box layout for my gui. My question is simple from what I see online boxlayout should stack elements on top of each other. However, I have a textarea(x,y) a toggle button and another textarea(x,y) when this is displayed there is a gap between my first text area and the toggle button and a gap between the toggle button and the 2nd textarea. Why are they not being stacked! Thanks,


Solution

  • Here's an example of an SSCCE that tries to demonstrate your problem. Perhaps you can modify it to show us what's going on:

    import java.awt.*;
    import javax.swing.*;
    
    public class BoxLayoutEg {
       public static void main(String[] args) {
          JTextArea area1 = new JTextArea(10, 20);
          JToggleButton toggleBtn = new JToggleButton("Foo");
          JTextArea area2 = new JTextArea(10, 20);
    
          JPanel toggleBtnPanel = new JPanel();
          toggleBtnPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
          // toggleBtnPanel.setLayout(new GridLayout());
          toggleBtnPanel.add(toggleBtn);
    
          JPanel mainJPanel = new JPanel();
          mainJPanel.setLayout(new BoxLayout(mainJPanel, BoxLayout.PAGE_AXIS));
    
          mainJPanel.add(new JScrollPane(area1));
          mainJPanel.add(toggleBtnPanel);
          mainJPanel.add(new JScrollPane(area2));
    
          JOptionPane.showMessageDialog(null, mainJPanel);
    
       }
    }