Search code examples
javaswingjpaneljmenubarjpanelmenu

No reason for menu bar to not work?


In this piece of code, I have absolutely no idea why my Menu bar doesn't work, may seem trivial and stupid to everyone here, but I'll really appreciate if someone can tell me why my Menu bar is not showing..

[Bonus] Also, I have no idea why "add(Canvas);" doesn't work, but I managed to find a solution to that with some research anyways, but if possible an explanation for that would be useful.

package drawer;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

import java.util.*;

public class Drawer {
public static void main(String[] args) {

        JMenuBar MenuBar; // My Menu code, which doesn't work..
        MenuBar = new JMenuBar();

        JMenu FileMenu = new JMenu("File");
        MenuBar.add(FileMenu);

        JMenuItem FileSaveMenu = new JMenuItem("Save");
        FileMenu.add(FileSaveMenu);


        JMenuItem FileLoadMenu = new JMenuItem("Load");
        FileMenu.add(FileLoadMenu);
        JMenuItem FileExitMenu = new JMenuItem("Exit");
        FileMenu.add(FileExitMenu);


        JMenu HelpMenu = new JMenu("Help");  
        JMenuItem FileAboutMenu = new JMenuItem("About");
        HelpMenu.add(FileAboutMenu); 

        JFrame MainWindow = new JFrame(); 
        FlowLayout layoutObj = new FlowLayout();
        MainWindow.setLayout(layoutObj);
        MainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        MainWindow.setSize(1600, 900); 
        MainWindow.setVisible(true);      


        JPanel ControlPanel = new JPanel();
        ControlPanel.setLayout(new FlowLayout(FlowLayout.TRAILING));     
        ControlPanel.setBorder(new TitledBorder(new EtchedBorder(), "Control Panel"));
        ControlPanel.setPreferredSize(new Dimension(200, 750));              
        MainWindow.getContentPane().add(ControlPanel);

        JPanel Canvas = new JPanel();
        Canvas.setLayout(new FlowLayout(FlowLayout.CENTER)); 
        Canvas.setBorder(new TitledBorder(new EtchedBorder(), "Canvas")); 
        Canvas.setPreferredSize(new Dimension(1300, 750)); 
        MainWindow.getContentPane().add(Canvas); // Where "add(Canvas);" doesn't work and this was the solution after researching..  

        JPanel MessageArea = new JPanel();
        MessageArea.setLayout(new FlowLayout(FlowLayout.CENTER));     
        MessageArea.setBorder(new TitledBorder(new EtchedBorder(), "Messages"));
        MessageArea.setPreferredSize(new Dimension(1500, 100));
        MainWindow.getContentPane().add(MessageArea);
    }

}

Solution

  • add

    MainWindow.setJMenuBar(MenuBar);
    

    at the end