Advanced Java Programming
Advanced Java Programming
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
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.
import java.awt.*;
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.
aFrame.add(aPanel);
1. Java AWT Label
• 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
// 5 rows, 80 columns
TextArea fullAddressTextArea = new TextArea(5, 80);
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.
aPanel.add(okButton));
aPanel.add(cancelButton));
okButton.addActionListener(controller2);
cancelButton.addActionListener(controller1);
Choice(): It creates a new choice menu.
The object of the Choice class is used to show a popup menu of choices.
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.
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:
North
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.
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.
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?
• 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
//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);
menuBar.add(fileMenu);
frame.setSize(300, 300);
frame.setVisible(true);
OutPut:
AWT FileDialog Class
Creates a file dialog window with the specified title for loading a file.
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.
• 2 String getDirectory()
• 4 FilenameFilter getFilenameFilter()
• 5 int getMode()
Indicates whether this file dialog box is for loading from a file or for saving to a file.
Cont..
Sets the directory of this file dialog window to be the specified directory.
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.
public AwtControlDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showFileDialogDemo(){
headerLabel.setText("Control in action: FileDialog");
controlPanel.add(showFileDialogButton);
mainFrame.setVisible(true);
}
}
outPut
Program using GridLayout:
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
// 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);
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
// Create a frame
// Create menus
// Create a button
Button button = new Button("Show Dialog");
button.setBounds(100, 100, 100, 50);
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
if (file != null) {
System.out.println("File to save: " + directory + file);
} else {
System.out.println("Save operation canceled.");
}
}
});
public MenuExample() {
// Create the frame
setTitle("AWT Menu Example");
setSize(400, 400);
// Create menus
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
setVisible(true);
}