Which containers may have a MenuBar

Frame.

In Core Java, the Frame and Applet containers can have a MenuBar. The MenuBar class is part of the AWT (Abstract Window Toolkit) library in Java, and it is used to create menus in GUI applications. The Frame class represents a top-level window with a title and border, and the Applet class represents an applet, which is a small Java program that runs within a web browser.

To add a MenuBar to a Frame or Applet, you typically create an instance of MenuBar, add one or more Menu objects to it, and then set the MenuBar as the menu bar for the Frame or Applet. Here’s a simple example:

java
import java.awt.*;

public class MenuBarExample extends Frame {
public MenuBarExample() {
// Create a MenuBar
MenuBar menuBar = new MenuBar();

// Create a Menu
Menu fileMenu = new Menu("File");

// Create MenuItems and add them to the Menu
MenuItem newItem = new MenuItem("New");
MenuItem openItem = new MenuItem("Open");
MenuItem exitItem = new MenuItem("Exit");

fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.addSeparator(); // Separator between items
fileMenu.add(exitItem);

// Add the Menu to the MenuBar
menuBar.add(fileMenu);

// Set the MenuBar for the Frame
setMenuBar(menuBar);

// Set other frame properties (size, visibility, etc.)
setSize(300, 200);
setVisible(true);
}

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

In this example, a Frame is created, a MenuBar is added to it, and a “File” menu with three items is added to the MenuBar. The MenuBar is then set as the menu bar for the Frame.