0% found this document useful (0 votes)
23 views

Advanced Java Programming

PPTs on the core concepts of advanced java programming

Uploaded by

Aayush Nalawade
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Advanced Java Programming

PPTs on the core concepts of advanced java programming

Uploaded by

Aayush Nalawade
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

AWT(Abstract Window ToolKit)

Introduction:

• Java AWT or Abstract Window Toolkit is an API used for developing GUI(Graphic User
Interfaces) or Window-Based Applications in Java. Java AWT is part of the Java Foundation
Classes (JFC) that provides a way to build platform-independent graphical applications.
• In this AWT tutorial, you will learn the basics of the AWT, including to create windows, buttons,
labels, and text fields. We will also learn how to add event listeners to components so that
they can respond to user input.
• Java AWT is an API used to create Graphical User Interface (GUI) or Windows-based Java
programs and Java AWT components are platform-dependent, which means they are shown in
accordance with the operating system’s view.
• AWT is heavyweight, which means that its components consume resources from the underlying
operating system (OS).
• The java.awt package contains AWT API classes such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
AWT Class Hierarchy

Component

Container Window Frame

Button Panel
List

Checkbox

Choice

Label

TextComponent TextField

TextArea
Java AWT Hierarchy
Description

•Components: AWT provides various components such as buttons, labels, text fields,
checkboxes, etc used for creating GUI elements for Java Applications
•Component is the superclass of most of the classes defined within the AWT. It is abstract.
•MenuComponent is another class which is similar to Component except it is the superclass
for all GUI items which can be displayed within a drop-down menu.
•The Component class defines - data and methods

• setBounds
• setSize
• setLocation
• setFont
• setEnabled
• setVisible
• setForeground
• setBackground
Types of Containers in Java AWT
There are four types of containers in Java AWT:
1.Window: Window is a top-level container that represents a graphical window or dialog box. The
Window class extends the Container class, which means it can contain other components, such as
buttons, labels, and text fields.
2.Panel: Panel is a container class in Java. It is a lightweight container that can be used for grouping
other components together within a window or a frame.
3.Frame: The Frame is the container that contains the title bar and border and can have menu bars.
4.Dialog: A dialog box is a temporary window an application creates to retrieve user input.

The Container class defined all the data and methods necessary for managing groups of Components
• add
• getComponent
• getMaximumSize
• getMinimumSize
• getPreferredSize
• remove
• removeAll
Windows and Frames

• The Window class defines a top-level Window with no Borders or Menu bar.

• Frame defines a top-level Window with Borders and a Menu Bar


•(Note:Frames are more commonly used than Windows)

• A Frame is a Container which can contain Components

Frame aFrame = new Frame(Hello Frame);


aFrame.setSize(100,100);
aFrame.setLocation(10,10);
aFrame.setVisible(true);
Frame Example with o/p

import java.awt.*;

public class CreateFrame { O/P


public static void main(String[] args) {
Frame f = new Frame();
Button b1 = new Button("Click me!");
Label l1 = new Label("Label");

b1.setBounds(50, 50, 100, 50);


l1.setBounds(50, 100, 100, 50);

f.setLayout(null);
f.setSize(300, 300);
f.setVisible(true);

f.add(b1);
f.add(l1);
}
}
Panels

• For any GUI application, the GUI portion can become quite complex.
• To manage the complexity, GUIs are broken down into groups of components. Each group
generally provides a unit of functionality.
• A Panel is a rectangular Container whose sole purpose is to hold and manage components within
a GUI.

Panel aPanel = new Panel();


aPanel.add(new Button("Ok"));
aPanel.add(new Button("Cancel"));

Frame aFrame = new Frame("Button Test");


aFrame.setSize(100,100);
aFrame.setLocation(10,10);

aFrame.add(aPanel);
1. Java AWT Label

Syntax of AWT Label


• public class Label extends Component implements Accessible

AWT Label Class Constructors


There are three types of Java AWT Label Class

• 1. Label():
Creates Empty Label.
• 2. Label(String str):
Constructs a Label with str as its name.
• 3. Label(String str, int x):

Constructs a label with the specified string and x as the specified alignment

Label aLabel = new Label("Enter password:");


aLabel.setAlignment(Label.RIGHT);
aPanel.add(aLabel);
2. Java AWT TextField

• Syntax of AWT TextField:


public class TextField extends TextComponent
TextField Class constructors
TextField class constructors are mentioned below:
• 1. TextField():
Constructs a TextField component.
• 2. TextField(String text):
Constructs a new text field initialized with the given string str to be displayed.
• 3. TextField(int col):
Creates a new text field(empty) with the given number of columns (col).
• 4. TextField(String str, int columns):
Creates a new text field(with String str in the display) with the given number of columns (col).
Java AWT TextField continued…

TextField emailTextField = new TextField();


TextField passwordTextField = new TextField();
passwordTextField.setEchoChar("*");

String userEmail = emailTextField.getText();


String userpassword = passwordTextField.getText();
3.TextArea

• This class displays multiple lines of optionally editable text.


• This class inherits several methods from TextComponent.
• TextArea also provides the methods: appendText(), insertText() and replaceText()

// 5 rows, 80 columns
TextArea fullAddressTextArea = new TextArea(5, 80);

String userFullAddress= fullAddressTextArea.getText();


4. Java AWT Checkbox

• Syntax of AWT Checkbox:


public class Checkbox extends Component implements ItemSelectable, Accessible

Checkbox Class Constructors


There are certain constructors in the AWT Checkbox class as mentioned below:
• 1. Checkbox():
Creates a checkbox with no label.
• 2. Checkbox(String str):
Creates a checkbox with a str label.
• 3. Checkbox(String str, boolean state, CheckboxGroup group):
Creates a checkbox with the str label, and sets the state in the mentioned group.
Java AWT Checkbox continued

• This class represents a GUI checkbox with a textual label.


• The Checkbox maintains a boolean state indicating whether it is checked or not.
• If a Checkbox is added to a CheckBoxGroup, it will behave like a radio button.

Checkbox creamCheckbox = new CheckBox("Cream");


Checkbox sugarCheckbox = new CheckBox("Sugar");

if (creamCheckbox.getState())
{
coffee.addCream();
}
5.Java AWT Buttons
• This class represents a push-button which displays some specified text.
• When a button is pressed, it notifies its Listeners. (More about Listeners in the next chapter).
• To be a Listener for a button, an object must implement the ActionListener Interface.
• There are two types of Button class constructors
• 1. Button( ):
Creates a Button with no label i.e. showing an empty box as a button.
• 2. Button(String str):
Creates a Button with String str as a label. For example if str=”Click Here” button with show click here
as the value.

Panel aPanel = new Panel();


Button okButton = new Button("Ok");
Button cancelButton = new Button("Cancel");

aPanel.add(okButton));
aPanel.add(cancelButton));

okButton.addActionListener(controller2);
cancelButton.addActionListener(controller1);
Choice(): It creates a new choice menu.

6. Java AWT Choice

• This class represents a dropdown list of Strings.


• Similar to a list in terms of functionality, but displayed differently.
• Only one item from the list can be selected at one time and the currently
selected element is displayed.

The object of the Choice class is used to show a popup menu of choices.

Syntax of AWT Choice:


public class Choice extends Component implements ItemSelectable, Accessible

AWT Choice Class constructor


Choice aChoice = new Choice();
aChoice.add(“Java");
aChoice.add(“CPP");
aChoice.add(“C");

String selectedLang= aChoice.getSelectedItem();


7.Java AWT List

• This class is a Component which displays a list of Strings.


• The list is scrollable, if necessary.
• Sometimes called Listbox in other languages.
• Lists can be set up to allow single or multiple selections.
• The list will return an array indicating which Strings are selected

The object of the AWT List class represents a list of text items.
Syntax of Java AWT List:
public class List extends Component implements ItemSelectable, Accessible
List aList = new List();
aList.add(“ Engineer");
aList.add(“Doctor");
aList.add(“Scientist");
aList.add(“Sociologist");
aList.setMultipleMode(true);
8.Layout Managers

• Since the Component class defines the setSize() and setLocation() methods, all Components
can be sized and positioned with those methods.
• Problem: the parameters provided to those methods are defined in terms of pixels. Pixel sizes may
be different (depending on the platform) so the use of those methods tends to produce GUIs which
will not display properly on all platforms.
• Solution: Layout Managers. Layout managers are assigned to Containers. When a Component is
added to a Container, its Layout Manager is consulted in order to determine the size and placement
of the Component.
• NOTE: If you use a Layout Manager, you can no longer change the size and location of a
Component through the setSize and setLocation methods.
• There are several different LayoutManagers, each of which sizes and positions its Components
based on an algorithm:
• FlowLayout
• BorderLayout
• GridLayout

• For Windows and Frames, the default LayoutManager is BorderLayout. For Panels, the default
LayoutManager is FlowLayout.
Flow Layout
• The algorithm used by the FlowLayout is to lay out Components like words on a page: Left to right,
top to bottom.
• It fits as many Components into a given row before moving to the next row.

Panel aPanel = new Panel();


aPanel.add(new Button("Ok"));
aPanel.add(new Button("Add"));
aPanel.add(new Button("Delete"));
aPanel.add(new Button("Cancel"));
Border Layout

The BorderLayout Manager breaks the Container up into 5 regions (North, South, East, West, and
Center).
When Components are added, their region is also specified:

Frame aFrame = new Frame();


aFrame.add("North", new Button("Ok"));
aFrame.add("South", new Button("Add"));
aFrame.add("East", new Button("Delete"));
aFrame.add("West", new Button("Cancel"));
aFrame.add("Center", new Button("Recalculate"));
Border Layout (cont)

The regions of the BorderLayout are defined as follows:

North

West Center East

South
Grid Layout

• The GridLayout class divides the region into a grid of equally sized rows and columns.
• Components are added left-to-right, top-to-bottom.
• The number of rows and columns is specified in the constructor for the LayoutManager.

Panel aPanel = new Panel();


GridLayout theLayout = new GridLayout(2,2);
aPanel.setLayout(theLayout);

aPanel.add(new Button("Ok"));
aPanel.add(new Button("Add"));
aPanel.add(new Button("Delete"));
aPanel.add(new Button("Cancel"));
Grid Layout
• The GridLayout class divides the region into a grid of equally sized rows and columns.
• Components are added left-to-right, top-to-bottom.
• The number of rows and columns is specified in the constructor for the LayoutManager.

Panel aPanel = new Panel();


GridLayout theLayout = new GridLayout(2,2);
aPanel.setLayout(theLayout);

aPanel.add(new Button("Ok"));
aPanel.add(new Button("Add"));
aPanel.add(new Button("Delete"));
aPanel.add(new Button("Cancel"));
What if dont want a LayoutManager?

• LayoutManagers have proved to be difficult and frustrating to deal with.


• The LayoutManager can be removed from a Container by invoking its setLayout method with a
null parameter.

Panel aPanel = new Panel();


aPanel.setLayout(null);
Graphics

• It is possible to draw lines and various shapes within a Panel under the AWT.
• Each Component contains a Graphics object which defines a Graphics Context which can be
obtained by a call to getGraphics().
• Common methods used in Graphics include:

• drawLine
• drawOval
• drawPolygon
• drawPolyLine
• drawRect
• drawRoundRect
• drawString
• draw3DRect
• fill3DRect
• fillArc
CardLayout

• The Java CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.
• Constructors of CardLayout Class
1.CardLayout(): creates a card layout with zero horizontal and vertical gap.
2.CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.

• public void next(Container parent): is used to flip to the next card of the given container.
• public void previous(Container parent): is used to flip to the previous card of the given
container.
• public void first(Container parent): is used to flip to the first card of the given container.
• public void last(Container parent): is used to flip to the last card of the given container.
• public void show(Container parent, String name): is used to flip to the specified card with the
given name.
GridBagLayout

• The Java GridBagLayout class is used to align components


vertically, horizontally or along their baseline.
• Each GridBagLayout object maintains a dynamic,
rectangular grid of cells.
• Each component occupies one or more cells known as its
display area.
• Each component associates an instance of
GridBagConstraints.
• With the help of the constraints object, we arrange the
component's display area on the grid.
• Constructor
• GridBagLayout(): The parameterless constructor is used
to create a grid bag layout manager.
Java AWT MenuItem & Menu
• MenuItem is a class that represents a simple labeled
menu item within a menu. It can be added to a menu
using the Menu.add(MenuItem mi) method.

• Syntax of Class Declaration MenuItem:


public class MenuItem extends MenuComponent
implements Accessible
Methods of the MenuItem Class:
public MenuItem(String label)- Constructs a new
MenuItem with the specified label
public String getLabel()- Returns the label of the menu
item
public void setLabel(String label)- Sets the label of
the menu item to the specified string.
public void addActionListener(ActionListener l)-
Adds an action listener to the menu item.
AWT Menu Class

• The Java AWT Menu class represents a pop-up menu


component in a graphical user interface (GUI) that can
contain a collection of MenuItem objects.
Syntax of Class Declaration of Menu
public Menu extends MenuItem
Methods of the Menu Class:
public Menu(String label)- Constructs a new menu
with the specified label.
public void add(MenuItem mi)- Adds the specified
menu item to the menu.
public void addSeparator()- Adds a separator between
menu items within the menu.
public MenuShortcut getShortcut()- Returns the
menu shortcut key associated with this menu.
/Java class to implement AWT Menu ///(Program to in Lab only)
// and MenuItem
import java.awt.*;
import java.awt.event.*;

//Driver Class
public class MenuExample {

//Main Method
public static void main(String[] args) {
Frame frame = new Frame("Menu Example");
MenuBar menuBar = new MenuBar();
frame.setMenuBar(menuBar);

// Create a "File" menu


Menu fileMenu = new Menu("File");
MenuItem openItem = new MenuItem("Open");
MenuItem saveItem = new MenuItem("Save");
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.addSeparator();

// Create an "Exit" menu item with an action listener


MenuItem exitItem = new MenuItem("Exit");
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});

//Added exit as item in MenuItem


fileMenu.add(exitItem);

menuBar.add(fileMenu);

frame.setSize(300, 300);
frame.setVisible(true);
OutPut:
AWT FileDialog Class

• FileDialog control represents a dialog window from


which the user can select a file.
• Class declaration
• Following is the declaration
for java.awt.FileDialog class:
public class FileDialog
Constructor:
1 FileDialog(Dialog parent)

Creates a file dialog for loading a file.


2 FileDialog(Dialog parent, String title)

Creates a file dialog window with the specified title for loading a file.

3 FileDialog(Dialog parent, String title, int mode)

Creates a file dialog window with the specified title for loading or
saving a file.
Cont..

• 4 FileDialog(Frame parent)
Creates a file dialog for loading a file.
• 5.FileDialog(Frame parent, String title)
Creates a file dialog window with the specified title for
loading a file.

• 6 FileDialog(Frame parent, String title, int mode)


Creates a file dialog window with the specified title for
loading or saving a file.
Class methods
• 1 void addNotify()

Creates the file dialog's peer.

• 2 String getDirectory()

Gets the directory of this file dialog.


• 3 String getFile()

Gets the selected file of this file dialog.

• 4 FilenameFilter getFilenameFilter()

Determines this file dialog's filename filter.

• 5 int getMode()

Indicates whether this file dialog box is for loading from a file or for saving to a file.
Cont..

• 6 protected String paramString()

Returns a string representing the state of this FileDialog window.

• 7 void setDirectory(String dir)

Sets the directory of this file dialog window to be the specified directory.

• 8 void setFile(String file)

Sets the selected file for this file dialog window to be the specified file.
• 9 void setFilenameFilter(FilenameFilter filter)

Sets the filename filter for this file dialog window to the specified filter.

• 10 void setMode(int mode)

Sets the mode of the file dialog.


Program
import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showFileDialogDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showFileDialogDemo(){
headerLabel.setText("Control in action: FileDialog");

final FileDialog fileDialog = new FileDialog(mainFrame,"Select file");


Button showFileDialogButton = new Button("Open File");
showFileDialogButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fileDialog.setVisible(true);
statusLabel.setText("File Selected :"
+ fileDialog.getDirectory() + fileDialog.getFile());
}
});

controlPanel.add(showFileDialogButton);
mainFrame.setVisible(true);
}
}
outPut
Program using GridLayout:
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class GridLayoutExample {


public static void main(String[] args) {
// Create a frame
Frame frame = new Frame("GridLayout Example");

// Set GridLayout with 3 rows and 2 columns


frame.setLayout(new GridLayout(3, 2));

// Add buttons to the frame


frame.add(new Button("Button 1"));
frame.add(new Button("Button 2"));
frame.add(new Button("Button 3"));
frame.add(new Button("Button 4"));
frame.add(new Button("Button 5"));
frame.add(new Button("Button 6"));
// Set the size of the frame
frame.setSize(300, 300);

// Make the frame visible


frame.setVisible(true);

// Add a window listener to close the window


frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
Program using GridBagLayout:

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class GridBagLayoutExample {


public static void main(String[] args) {
// Create a frame
Frame frame = new Frame("GridBagLayout Example");

// Set GridBagLayout
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
// Button 1 - placed at (0,0)
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
frame.add(new Button("Button 1"), gbc);

// Button 2 - placed at (1,0), spans 2 columns


gbc.gridx = 1;
gbc.gridy = 0;
gbc.grid
Program using MenuBar:
import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

public class MenuBarExample {

public static void main(String[] args) {

// Create a frame

Frame frame = new Frame("MenuBar Example");

// Create a menu bar

MenuBar menuBar = new MenuBar();

// Create menus

Menu fileMenu = new Menu("File");

Menu editMenu = new Menu("Edit");

// Create menu items

MenuItem newFile = new MenuItem("New");

MenuItem openFile = new MenuItem("Open");

MenuItem saveFile = new MenuItem("Save");


// Add menu items to the File menu
fileMenu.add(newFile);
fileMenu.add(openFile);
fileMenu.add(saveFile);
fileMenu.addSeparator(); // Adds a separator line
fileMenu.add(exit);

// Add the File and Edit menus to the menu bar


menuBar.add(fileMenu);
menuBar.add(editMenu);

// Add the menu bar to the frame


frame.setMenuBar(menuBar);

// Set the size of the frame


frame.setSize(400, 300);

// Make the frame visible


frame.setVisible(true);
// Add action listener for Exit menu item
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});

// Add a window listener to close the window


frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
Program with a Dialog Box:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class DialogBoxExample {


public static void main(String[] args) {
// Create a frame
Frame frame = new Frame("Dialog Box Example");

// Create a button
Button button = new Button("Show Dialog");
button.setBounds(100, 100, 100, 50);

// Add button to the frame


frame.add(button);

// Set the size of the frame


frame.setSize(300, 300);
// Make the frame visible
frame.setVisible(true);

// Add action listener to the button


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Create a dialog box
Dialog dialog = new Dialog(frame, "This is a Dialog", true);
dialog.setLayout(new FlowLayout());
dialog.setSize(200, 150);

// Add a label to the dialog


Label label = new Label("Dialog Box Example");
dialog.add(label);

// Add an OK button to close the dialog


Button okButton = new Button("OK");
dialog.add(okButton);
// Add action listener to the OK button to close the dialog
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}
});

// Make the dialog visible


dialog.setVisible(true);
}
});

// Add a window listener to close the window


frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
Program with FileDialog:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class FileDialogExample {


public static void main(String[] args) {
// Create a frame
Frame frame = new Frame("FileDialog Example");

// Create buttons for opening and saving files


Button openButton = new Button("Open File");
Button saveButton = new Button("Save File");

// Set layout and add buttons to the frame


frame.setLayout(new FlowLayout());
frame.add(openButton);
frame.add(saveButton);

// Set the size of the frame


frame.setSize(300, 150);

// Make the frame visible


frame.setVisible(true);

// Add action listener to the Open File button


openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Create a file dialog for opening files
FileDialog fileDialog = new FileDialog(frame, "Open File", FileDialog.LOAD);
fileDialog.setVisible(true);

// Get the selected file and directory


String directory = fileDialog.getDirectory();
String file = fileDialog.getFile();
if (file != null) {
System.out.println("File selected: " + directory + file);
} else {
System.out.println("File selection canceled.");
}
}
});

// Add action listener to the Save File button


saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Create a file dialog for saving files
FileDialog fileDialog = new FileDialog(frame, "Save File", FileDialog.SAVE);
fileDialog.setVisible(true);

// Get the selected file and directory


String directory = fileDialog.getDirectory();
String file = fileDialog.getFile();

if (file != null) {
System.out.println("File to save: " + directory + file);
} else {
System.out.println("Save operation canceled.");
}
}
});

// Add a window listener to close the window


frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
Java AWT Menu Example
import java.awt.*;
import java.awt.event.*;

public class MenuExample extends Frame implements ActionListener {

MenuItem newItem, openItem, saveItem, exitItem;

public MenuExample() {
// Create the frame
setTitle("AWT Menu Example");
setSize(400, 400);

// Create a menu bar


MenuBar menuBar = new MenuBar();

// Create menus
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");

// Create menu items


newItem = new MenuItem("New");
openItem = new MenuItem("Open");
saveItem = new MenuItem("Save");
exitItem = new MenuItem("Exit");

// Add menu items to the File menu


fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.addSeparator(); // Adds a separator line
fileMenu.add(exitItem);

// Add menu items to the Edit menu (can be customized further)


editMenu.add(new MenuItem("Cut"));
editMenu.add(new MenuItem("Copy"));
editMenu.add(new MenuItem("Paste"));

// Add action listeners for menu items


newItem.addActionListener(this);
openItem.addActionListener(this);
saveItem.addActionListener(this);
exitItem.addActionListener(this);

// Add menus to the menu bar


menuBar.add(fileMenu);
menuBar.add(editMenu);

// Set the menu bar for the frame


setMenuBar(menuBar);

// Closing the frame


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});

setVisible(true);
}

// Handle menu item actions


public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
switch (command) {
case "New":
System.out.println("New File");
break;
case "Open":
System.out.println("Open File");
break;
case "Save":
System.out.println("Save File");
break;
case "Exit":
System.exit(0);
break;
default:
System.out.println(command + " selected");
}
}

public static void main(String[] args) {


new MenuExample();
}
}

You might also like