To create a menu bar in Java AWT, we can use the MenuBar and Menu classes. Here is an example code that creates a menu bar with a menu:
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
public class MyMenuBar {
public static void main(String[] args) {
Frame frame = new Frame("My Window");
MenuBar menuBar = new MenuBar();
Menu fileMenu = new Menu("File");
MenuItem newItem = new MenuItem("New");
MenuItem openItem = new MenuItem("Open");
MenuItem exitItem = new MenuItem("Exit");
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
menuBar.add(fileMenu);
frame.setMenuBar(menuBar);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
In this example code, we create a MenuBar object and a Menu object. We also create three MenuItem objects for the menu. We add the menu items to the menu using the add method and add a separator between the "Open" and "Exit" items using the addSeparator method. We add the menu to the menu bar using the add method and set the menu bar of the frame using the setMenuBar method.
When we run this code, a window with a menu bar containing the "File" menu will be displayed. When we click on the "File" menu, we will see the "New", "Open", and "Exit" items.