Home > Enterprise >  Java Swing: Why are my panels layered? I can't see my first panel
Java Swing: Why are my panels layered? I can't see my first panel

Time:05-05

I'm trying to have one panel appear under the other (textPanel to appear under mainPanel).

But instead, textPanel is appearing overtop of mainPanel:

    FlatLightLaf.setup();
    FlatLightLaf.supportsNativeWindowDecorations();
    UIManager.setLookAndFeel(new FlatLightLaf()); 
    
    JFrame frame = new JFrame();
    frame.setTitle("Title");
    frame.setSize(640, 480);
    
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("File");
    JMenuItem menuFileSave = new JMenuItem("Save");
    menuFileSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
    
    menu.add(menuFileSave);
    
    menuBar.add(menu);
    
    FlowLayout mainLayout = new FlowLayout(FlowLayout.LEFT);
    
    frame.setJMenuBar(menuBar);
    
    JPanel mainPanel = new JPanel(new BorderLayout());
    
    String datesString[] = {"Tuesday May-03-2022", "Monday May-02-2022"};
    @SuppressWarnings("rawtypes")
    JComboBox dateDropDown = new JComboBox<>(datesString);
    dateDropDown.setFont(new Font("Calibri", Font.PLAIN, 17));
    dateDropDown.setVisible(true);
    
    mainPanel.add(dateDropDown);

    mainPanel.setVisible(true);
    frame.add(mainPanel);
    
    JPanel textPanel = new JPanel(new BorderLayout());
    
    JTextArea textArea = new JTextArea();
    textPanel.add(textArea);

    textPanel.setVisible(true);
    frame.add(textPanel);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

How do I ensure textPanel goes below mainPanel on its own row/line, and not overtop of it?

CodePudding user response:

The default, when adding one component, without further arguments, to a JFrame is that the component in question will take up the entire client area, since JFrame uses a BorderLayout by default. So, your solution is to use a further argument, telling it to add it at the bottom of the layout:

frame.add(textPanel, BorderLayout.PAGE_END);
  • Related