Unit-5 (OOPS With Java)
Unit-5 (OOPS With Java)
PRASHANT TOMAR
SWING
• Swing has about four times the number of User Interface [UI] components as AWT and
is part of the standard Java distribution.
• By today’s application GUI requirements, AWT is a limited implementation, not quite
capable of providing the components required for developing complex GUI’s required
in modern commercial applications.
• The AWT component set has quite a few bugs and really does take up a lot of system
resources when compared to equivalent Swing resources. Netscape introduced its
Internet Foundation Classes [IFC] library for use with Java. Its Classes became very
popular with programmers creating GUI’s for commercial applications.
• Swing is a Set Of API ( API- Set Of Classes and Interfaces )
• Swing is Provided to Design Graphical User Interfaces
• Swing is an Extension library to the AWT (Abstract Window Toolkit)
• Includes New and improved Components that have been enhancing the looks and Functionality of GUIs’
• Swing can be used to build(Develop) The Standalone swing GUI Apps Also as Servlets And Applets
• It Employs model/view design architecture
• Swing is more portable and more flexible than AWT, The Swing is built on top of the AWT
• Swing is Entirely written in Java
• Java Swing Components are Platform-independent And The Swing Components are lightweight
• Swing Supports a Pluggable look and feels And Swing provides more powerful components
• such as tables, lists, Scrollpanes, Colourchooser, tabbedpane, etc.
• Further Swing Follows MVC
Features Of Swing Class
• Pluggable look and feel
• Uses MVC architecture
• Lightweight Components
• Platform Independent
• Advanced features such as JTable, JTabbedPane, JScollPane, etc.
• Java is a platform-independent language and runs on any client machine, the GUI look
and feel, owned and delivered by a platform-specific O/S, simply does not affect an
application’s GUI constructed using Swing components.
• Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane,
slider, colorpicker, and table controls.
• Lightweight Components: Starting with the JDK 1.1, its AWT-supported
lightweight component development. For a component to qualify as lightweight,
it must not depend on any non-Java [O/s based) system classes. Swing
components have their own view supported by Java’s look and feel classes.
• Pluggable Look and Feel: This feature enables the user to switch the look and
feel of Swing components without restarting an application. The Swing library
supports components’ look and feels that remain the same across all platforms
wherever the program runs. The Swing library provides an API that gives real
flexibility in determining the look and feel of the GUI of an application
• Highly customizable – Swing controls can be customized in a very easy way as
visual appearance is independent of internal representation.
LAYOUT MANAGEMENT - SWING
• A container uses a layout manager to position all its components. A layout manager computes four properties (x, y, width, and
• A layout manager is an object of a Java class that implements the LayoutManager interface or LayoutManager2 interface.
LayoutManager2 interface inherits from the LayoutManager interface. Both interfaces are in the [Link] package.
• FlowLayout
• BorderLayout
• CardLayout
• BoxLayout
• GridLayout
• GridBagLayout
• GroupLayout
• SpringLayout
• Every container has a default layout manager. The default layout manager for the
content pane of a JFrame is BorderLayout.
• For a JPanel, the default layout manager is FlowLayout.
• We can change the default layout manager of a container by using its setLayout()
method.
• To remove a layout manager, we can pass null to the setLayout() method.
• The getLayout() method of a container returns the reference of the layout
manager the container is currently using.
• The following code shows how to set FlowLayout as the layout manager for the
content pane of a JFrame
BorderLayout
• Every content pane is initialized to use a BorderLayout. (As Using Top-Level
Containers explains, the content pane is the main container in all frames, applets,
and dialogs.) A BorderLayout places components in up to five areas: top, bottom,
left, right, and center. All extra space is placed in the center area. Tool bars that
are created using JToolBar must be created within a BorderLayout container, if
you want to be able to drag and drop the bars away from their starting positions.
BoxLayout
• The BoxLayout class puts components in a single row or column. It respects the
components' requested maximum sizes and also lets you align components.
CardLayout
• The CardLayout class lets you implement an area that contains different
components at different times. A CardLayout is often controlled by a combo box,
with the state of the combo box determining which panel (group of components)
the CardLayout displays. An alternative to using CardLayout is using a tabbed
pane, which provides similar functionality but with a pre-defined GUI.
FlowLayout
• FlowLayout is the default layout manager for every JPanel. It simply lays out
components in a single row, starting a new row if its container is not sufficiently
wide. Both panels in CardLayoutDemo, shown previously, use FlowLayout.
•
GridBagLayout
• GridBagLayout is a sophisticated, flexible layout manager. It aligns components by
placing them within a grid of cells, allowing components to span more than one
cell. The rows in the grid can have different heights, and grid columns can have
different widths.
GridLayout
• GridLayout simply makes a bunch of components equal in size and displays them
in the requested number of rows and columns.
GroupLayout
• GroupLayout is a layout manager that was developed for use by GUI builder tools,
but it can also be used manually. GroupLayout works with the horizontal and
vertical layouts separately. The layout is defined for each dimension
independently. Consequently, however, each component needs to be defined
twice in the layout. The Find window shown above is an example of a
GroupLayout.
SpringLayout
• SpringLayout is a flexible layout manager designed for use by GUI builders. It lets
you specify precise relationships between the edges of components under its
control. For example, you might define that the left edge of one component is a
certain distance (which can be dynamically calculated) from the right edge of a
second component. SpringLayout lays out the children of its associated container
according to a set of constraints.
Text Fields
• JTextField is a part of [Link] package. The class JTextField is a component that allows
editing of a single line of text. JTextField inherits the JTextComponent class and uses the
interface SwingConstants.
• Swing text components display text and optionally allow the user to edit the text. Programs
need text components for tasks ranging from the straightforward (enter a word and press
Enter) to the complex (display and edit styled text with embedded images in an Asian
language).
• Swing provides six text components, along with supporting classes and interfaces that meet
even the most complex text requirements. In spite of their different uses and capabilities, all
Swing text components inherit from the same superclass, JTextComponent, which provides a
highly-configurable and powerful foundation for text manipulation.
The constructor of the class are :
• JTextField() : constructor that creates a new TextField
• JTextField(int columns) : constructor that creates a new empty TextField with
specified number of columns.
• JTextField(String text) : constructor that creates a new empty text field initialized
with the given string.
• JTextField(String text, int columns) : constructor that creates a new empty
textField with the given string and a specified number of columns .
• JTextField(Document doc, String text, int columns) : constructor that creates a
textfield that uses the given text storage model and the given number of
columns.
Methods of the JTextField
• setColumns(int n) : set the number of columns of the text field.
• setFont(Font f) : set the font of text displayed in text field.
• addActionListener(ActionListener l) : set an ActionListener to the text field.
• int getColumns() : get the number of columns in the textfield.
// addActionListener to button
[Link](te);
• setColumns(int c) : sets the number of columns of the text area to given integer.
• setRows(int r) : sets the number of rows of the text area to given integer.
// JFrame
static JFrame f;
// JButton
static JButton b;
// label to display text
static JLabel l;
// text area
static JTextArea jt;
// default constructor
text()
{
}
// main class
public static void main(String[] args)
{
// create a new frame to store text field and button
f = new JFrame("textfield");
// addActionListener to button
[Link](te);
Text Also known simply as text fields, text controls can display only one line of editable text. JTextField and its
Controls subclasses JPasswordFi
Like buttons, they generate action events. Use them to get a small amount of textual eld and JFormattedText
information from the user and perform an action after the text entry is complete. Field
Plain Text JTextArea can display multiple lines of editable text. Although a text area can display JTextArea
Areas
text in any font, all of the text is in the same font. Use a text area to allow the user to
enter unformatted text of any length or to display unformatted help information.
Styled Text A styled text component can display editable text using more than one font. Some JEditorPane
Areas and its subclass
styled text components allow embedded images and even embedded components. JTextPane
Styled text components are powerful and multi-faceted components suitable for high-
end needs, and offer more avenues for customization than the other text components.
Because they are so powerful and flexible, styled text components typically require
more initial programming to set up and use. One exception is that editor panes can be
easily loaded with formatted text from a URL, which makes them useful for displaying
uneditable help information.
JButton
• The class JButton is an implementation of a push button. This component has a
label and generates an event when pressed. It can also have an Image.
• Class Constructors
[Link]. Constructor & Description
JButton()
1
Creates a button with no set text or icon.
JButton(Action a)
2
Creates a button where properties are taken from the Action supplied.
JButton(Icon icon)
3
Creates a button with an icon.
JButton(String text)
4
Creates a button with the text.
JButton(String text, Icon icon)
5
Creates a button with an initial text and an icon.
[Link]. Method & Description
AccessibleContext getAccessibleContext()
1
Gets the AccessibleContext associated with this JButton.
String getUIClassID()
2 Returns a string that specifies the name of the L&F class which renders this component.
boolean isDefaultButton()
3 Gets the value of the defaultButton property, which if true means that this button is the current default button for its JRootPane.
boolean isDefaultCapable()
4
Gets the value of the defaultCapable property.
protected String paramString()
5
Returns a string representation of this JButton.
void removeNotify()
Overrides [Link] to check if this button is currently set as the default button on the RootPane. And if so, sets
6 the RootPane's default button to null to ensure the RootPane doesn't hold onto an invalid button reference.
void updateUI()
8
Resets the UI property to a value from the current look and feel.
import [Link].*;
import [Link].*;
import [Link].*;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
[Link]();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
[Link](400,400);
[Link](new GridLayout(3, 1));
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
[Link](0);
}
});
headerLabel = new JLabel("", [Link]);
statusLabel = new JLabel("",[Link]);
[Link](350,100);
[Link](headerLabel);
[Link](controlPanel);
[Link](statusLabel);
[Link](true);
}
private static ImageIcon createImageIcon(String path, String description) {
[Link] imgURL = [Link](path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
[Link]("Couldn't find file: " + path);
return null;
}
}
private void showButtonDemo(){
[Link]("Control in action: Button");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Ok Button clicked.");
}
});
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Submit Button clicked.");
}
});
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Cancel Button clicked.");
}
});
[Link](okButton);
[Link](javaButton);
[Link](cancelButton);
[Link](true);
}
}
JCheckBox
• The class JCheckBox is an implementation of a check box - an item that can be
selected or deselected, and which displays its state to the user.
[Link]. Constructor & Description
JCheckBox()
1
Creates an initially unselected check box button with no text and no icon.
JCheckBox(Action a)
2
Creates a checkbox where the properties are taken from the Action supplied.
JCheckBox(Icon icon)
3
Creates an initially unselected checkbox with an icon.
JCheckBox(Icon icon, boolean selected)
4 Creates a checkbox with an icon and specifies whether or not it is initially selected.
JCheckBox(String text)
5
Creates an initially unselected checkbox with text.
JCheckBox(String text, boolean selected)
6 Creates a checkbox with the text and specifies whether or not it is initially selected.
AccessibleContext getAccessibleContext()
1 Gets the AccessibleContext associated with this JCheckBox.
String getUIClassID()
2 Returns a string that specifies the name of the L&F class which renders this component.
boolean isBorderPaintedFlat()
3 Gets the value of the borderPaintedFlat property.
void setBorderPaintedFlat(boolean b)
5 Sets the borderPaintedFlat property, which gives a hint to the look and feel as to the
appearance of the checkbox border.
void updateUI()
6 Resets the UI property to a value from the current look and feel
import [Link].*;
import [Link].*;
import [Link].*;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
[Link]();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
[Link](400,400);
[Link](new GridLayout(3, 1));
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
[Link](0);
}
});
headerLabel = new JLabel("", [Link]);
statusLabel = new JLabel("",[Link]);
[Link](350,100);
[Link](headerLabel);
[Link](controlPanel);
[Link](statusLabel);
[Link](true);
}
private void showCheckBoxDemo(){
[Link]("Control in action: CheckBox");
[Link](KeyEvent.VK_C);
[Link](KeyEvent.VK_M);
[Link](KeyEvent.VK_P);
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("Apple Checkbox: "
+ ([Link]()==1?"checked":"unchecked"));
}
});
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("Mango Checkbox: "
+ ([Link]()==1?"checked":"unchecked"));
}
});
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("Peer Checkbox: "
+ ([Link]()==1?"checked":"unchecked"));
}
});
[Link](chkApple);
[Link](chkMango);
[Link](chkPeer);
[Link](true);
}
}
JRadioButton
• The class JRadioButton is an implementation of a radio button - an item that can
be selected or deselected, and which displays its state to the user.
[Link]. Constructor & Description
JRadioButton()
1 Creates an initially unselected radio button with no set text.
JRadioButton(Action a)
2
Creates a radiobutton where properties are taken from the Action supplied.
JRadioButton(Icon icon)
3 Creates an initially unselected radio button with the specified image but no text
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JRadioButton.
1
String getUIClassID()
Returns the name of the L&F class that renders this component.
2
void updateUI()
Resets the UI property to a value from the current look and feel.
4
import [Link].*;
import [Link].*;
import [Link].*;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
[Link]();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
[Link](400,400);
[Link](new GridLayout(3, 1));
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
[Link](0);
}
});
headerLabel = new JLabel("", [Link]);
statusLabel = new JLabel("",[Link]);
[Link](350,100);
[Link](headerLabel);
[Link](controlPanel);
[Link](statusLabel);
[Link](true);
}
private void showRadioButtonDemo(){
[Link]("Control in action: RadioButton");
[Link](KeyEvent.VK_C);
[Link](KeyEvent.VK_M);
[Link](KeyEvent.VK_P);
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("Apple RadioButton: "
+ ([Link]()==1?"checked":"unchecked"));
}
});
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("Mango RadioButton: "
+ ([Link]()==1?"checked":"unchecked"));
}
});
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("Peer RadioButton: "
+ ([Link]()==1?"checked":"unchecked"));
}
});
[Link](radApple);
[Link](radMango);
[Link](radPeer);
[Link](radApple);
[Link](radMango);
[Link](radPeer);
[Link](true);
}
}
JList
• The class JList is a component which displays a list of objects and allows the user
to select one or more items. A separate model, ListModel, maintains the contents
of the list.
[Link]. Constructor & Description
JList()
1 Constructs a JList with an empty, read-only, model.
JList(ListModel dataModel)
2 Constructs a JList that displays elements from the specified, non-null, model.
JList(Object[] listData)
3 Constructs a JList that displays the elements in the specified array.
JList(Vector<?> listData)
4 Constructs a JList that displays the elements in the specified Vector.
import [Link].*;
import [Link].*;
import [Link].*;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
[Link]();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
[Link](400,400);
[Link](new GridLayout(3, 1));
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
[Link](0);
}
});
headerLabel = new JLabel("", [Link]);
statusLabel = new JLabel("",[Link]);
[Link](350,100);
[Link](headerLabel);
[Link](controlPanel);
[Link](statusLabel);
[Link](true);
}
private void showListDemo(){
[Link]("Control in action: JList");
final DefaultListModel fruitsName = new DefaultListModel();
[Link]("Apple");
[Link]("Grapes");
[Link]("Mango");
[Link]("Peer");
[Link](ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
[Link](0);
[Link](3);
[Link](true);
}
}
JScrollBar
• The class JScrollBar is an implementation of scrollbar.
[Link]. Constructor & Description
JScrollBar()
1 Creates a vertical scrollbar with the initial values.
JScrollBar(int orientation)
2 Creates a scrollbar with the specified orientation and the initial values.
JScrollBar(int orientation, int value, int extent, int min, int max)
3 Creates a scrollbar with the specified orientation, value, extent, minimum, and maximum.
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
[Link]();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
[Link](400,400);
[Link](new GridLayout(3, 1));
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
[Link](0);
}
});
headerLabel = new JLabel("", [Link]);
statusLabel = new JLabel("",[Link]);
[Link](350,100);
[Link](headerLabel);
[Link](controlPanel);
[Link](statusLabel);
[Link](true);
}
private void showScrollbarDemo() {
[Link]("Control in action: JScrollbar");
[Link](new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
[Link]("Horozontal: "
+[Link]()
+" ,Vertical: "
+ [Link]());
}
});
[Link](new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
[Link]("Horozontal: "
+[Link]()
+" ,Vertical: "+ [Link]());
}
});
[Link](horizontalScroller);
[Link](verticalScroller);
[Link](true);
}
}
Windows Menus
• A menu provides a space-saving way to let the user choose one of several options.
Other components with which the user can make a one-of-many choice include combo
boxes, lists, radio buttons, spinners, and tool bars. If any of your menu items performs
an action that is duplicated by another menu item or by a tool-bar button.
• Menus are unique in that, by convention, they aren't placed with the other components
in the UI. Instead, a menu usually appears either in a menu bar or as a popup menu. A
menu bar contains one or more menus and has a customary, platform-dependent
location — usually along the top of a window. A popup menu is a menu that is invisible
until the user makes a platform-specific mouse action, such as pressing the right mouse
button, over a popup-enabled component. The popup menu then appears under the
cursor.
• The following figure shows many menu-related components: a menu bar, menus,
menu items, radio button menu items, check box menu items, and separators. As
you can see, a menu item can have either an image or text, or both. You can also
specify other properties, such as font and color.
Menu Component Hierarchy
import [Link].*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
[Link](i1); [Link](i2); [Link](i3);
[Link](i4); [Link](i5);
[Link](submenu);
[Link](menu);
[Link](mb);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new MenuExample();
}}
Dialog Boxes
• A Dialog window is an independent sub window meant to carry temporary notice apart
from the main Swing Application Window. Most Dialogs present an error message or
warning to a user, but Dialogs can present images, directory trees, or just about
anything compatible with the main Swing Application that manages them.
• For convenience, several Swing component classes can directly instantiate and display
dialogs. To create simple, standard dialogs, you use the JOptionPane class. The
ProgressMonitor class can put up a dialog that shows the progress of an operation. Two
other classes, JColorChooser and JFileChooser, also supply standard dialogs. To bring up
a print dialog, you can use the Printing API. To create a custom dialog, use the JDialog
class directly.
• The code for simple dialogs can be minimal. For example, here is an informational
dialog:
Windows
Java look
Icon description look and
and feel
feel
question
Information
Warning
Error
//default title and icon
[Link](frame, "Eggs are not supposed to be green.");
• Change in the state of an object is known as event i.e. event describes the change
in state of source. Events are generated as result of user interaction with the
graphical user interface components. For example, clicking on a button, moving
the mouse, entering a character through keyboard, selecting an item from list,
scrolling the page are the activities that causes an event to happen.
• An event can be defined as changing the state of an object or behavior by
performing actions. Actions can be a button click, cursor movement, keypress
through keyboard or page scrolling, etc.
• The [Link] package can be used to provide various event classes.
Classification of Events
• Foreground Events
• Background Events
Foreground Events
• Foreground events are the events that require user interaction to generate, i.e.,
foreground events are generated due to interaction by the user on components
in Graphic User Interface (GUI).Interactions are nothing but clicking on a button,
scrolling the scroll bar, cursor moments, etc.
Background Events
• Events that don’t require interactions of users to generate are known as
background events. Examples of these events are operating system
failures/interrupts, operation completion, etc.
• It is a mechanism to control the events and to decide what should happen after
an event occur. To handle the events, Java follows the Delegation Event model.
• To perform Event Handling, we need to register the source with the listener.
• Registering the Source With Listener
• Different Classes provide different registration methods.
Syntax:
addTypeListener()
ActionEvent ActionListener actionPerformed() An event that indicates that a component-defined action occurred like a
button click or selecting an item from the menu-item list.
AdjustmentEvent AdjustmentListener adjustmentValueChanged() The adjustment event is emitted by an Adjustable object like Scrollbar.
ComponentEvent ComponentListener componentResized(), componentMoved(), An event that indicates that a component moved, the size changed or
componentShown(), componentHidden() changed its visibility.
ContainerEvent ContainerListener componentRemoved() and componentAdded() When a component is added to a container (or)removed from it, then this
event is generated by a container object.
FocusEvent FocusListener focusLost() and focusGained() These are focus-related events, which include focus, focusin, focusout, and
blur.
ItemEvent ItemListener itemStateChanged() An event that indicates whether an item was selected or not.
KeyEvent KeyListener keyPressed(), keyReleased(), keyTyped(). An event that occurs due to a sequence of keypresses on the keyboard.
MouseEvent MouseListener mouseClicked(), mousePressed(), The events that occur due to the user interaction with the mouse (Pointing
&MouseMotionListene mouseEntered(), mouseExited() , Device).
r mouseReleased() are the mouseListener methods.
mouseDregged() and mouseMoved() are the
MouseMotionListener() methods.
MouseWheelEvent MouseWheelListener mouseWheelMoved(). An event that specifies that the mouse wheel was rotated in a component.
TextEvent TextListener textChanged() An event that occurs when an object’s text changes.
WindowEvent WindowListener windowActivated(), windowDeactivated(), An event which indicates whether a windowhas changed its status or not.
windowOpened(), windowClosed(),
windowClosing(), windowIconfied() and
windowDeiconified().
import [Link].*; // main() method start
import [Link].*; public static void main(String[] args){
//create class EventHandlingExample1 to pe
rform event handling within the class // create an instance of EventHandlingExample1
public class EventHandlingExample1 { EventHandlingExample1 obj = new EventHand
lingExample1();
// create variables for Frame, Label and Panel [Link]();
private Frame frame; }
// create makeGUI() method to create a UI to perform user int
private Label header; eraction
private Label status; private void makeGUI(){
private Panel panel;
// initialize Frame
// default constructor frame = new Frame("Event Handling Example");
public EventHandlingExample1(){
// set frame size by using setSize() method
makeGUI(); [Link](400,400);
}
//set frame layout by using setLayout() method //initialize status and set its alignment and size
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
• [Link] Adapter classes
Adapter class Listener interface
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
// importing the necessary libraries
import [Link].*;
import [Link].*;
// main method
public static void main(String[] args) {
new AdapterExample();
}
}
Java AWT
• Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface
(GUI) or windows-based applications in Java.
• The [Link] package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
• Java AWT calls the native platform calls the native platform (operating systems)
subroutine for creating API components like TextField, ChechBox, button, etc.
Components
• All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT,
there are classes for each component as shown in above diagram. In order to place every
component in a particular position on a screen, we need to add them to a container.
Container
• The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
• It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components.
• There are four types of containers in Java AWT:
[Link]
[Link]
[Link]
[Link]
Window
• The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window. We need to create an
instance of Window class to create this container.
Panel
• The Panel is the container that doesn't contain title bar, border or menu bar. It is
generic container for holding the components. It can have other components like
button, text field etc. An instance of Panel class creates a container, in which we
can add components.
Frame
• The Frame is the container that contain title bar and border and can have menu
bars. It can have other components like button, text field, scrollbar etc. Frame is
most widely used container while developing an AWT application.
Method Description
// creating a button
Button b = new Button("Click Me!!");
// setting button position on screen
[Link](30,100,80,30);
// adding button into frame
add(b);
// frame size 300 width and 300 height
setSize(300,300);
// setting the title of Frame
setTitle("This is our basic AWT example");
// no layout manager
setLayout(null);
// now frame will be visible, by default it is not visible
setVisible(true);
}
// main method
public static void main(String args[]) {
// creating instance of Frame class
AWTExample1 f = new AWTExample1();
}
}
Graphics Programming
• Most of the programs we have seen involve two classes: an application class and
a tester class that contains a main method. A graphics program also consists of
two classes: a component and a frame viewer. The component contains the
graphics code. The frame viewer contains main, which creates a window (called a
frame), creates a component, adds the component to the window, then displays
the window.
• Frame
• frame viewer is simple. Main creates a JFrame, makes it pretty, adds a graphics
component, then displays itself.
public class FrameViewer {