AWT and Swing
AWT and Swing
Object
Component
Container
Window Panel
Frame Applet
JFrame JApplet
Component
• It is an abstract class and all GUI component that
interacts with the user are subclasses of component
class
• It defines various methods for managing events such
as keyboard and mouse.
• It also defines attributes to store current foreground
and background color and font.
Container
• It inherits various methods and attributes of component class
and having additional methods of nesting other component
objects.
• A container positions various GUI components within it.
Windows
• This class is used to create a top level window.
Generally, windows objects are not created directly,
subclass of window is used to place on the desktop.
Frame
Frame class is a subclass of window and it
has title bar, menu bar, borders etc.
Frame( ) constructor is used to create Frame
windows.
There are two types of frame constructors
Frame ( ) ;
Frame ( String title);
There are two important methods which are
important to decide the size of the frame
and visibility of the frame.
To decide the size of the frame setSize( )
method is used.
Frame
• Syntax :
• setSize( int width, int height);
• Example:
• setSize( 300, 200);
• To visible the frame after creation we use
setVisible( ) method.
• Syntax :
• setVisible(VisibleFlag);
• Example :
• setVisible(True);
• Example : FrameDemo.java
JFrame
• Constructors :
• JFrame( ) : Constructs s new frame that is
initially invisible
• JFrame(String titel) : creates a new,
initially invisible frame with the specified
•
title.
Methods :
• void setTitle(String title)
• void setSize(int width, int height)
• void setLocation( int x, int y) (left,top)
• void setDefaultCloseOperation(int op)
• JFrame.EXIT_ON_CLOSE
• JFrame.HIDE_ON_CLOSE
• JFrame.DO_NOTHING_ON_CLOSE
• JFrame.DISPOSE_ON_CLOSE
• void setLayout(LayoutManager manager)
AWT
• At the time of creation of the Java 1.0 for graphics User
Interface , Sun provides the Abstract Window Toolkit.
• This is one of reasons of the popularity of Java of use of AWT
for user interface.
• Abstract window programming provides the magic in the look
for the Window, and provides the better look for the user
environment.
• There are various popular classes which are having AWT are
as follows.
• Applets • List
• Button • Frame
• Label • Dialog
• Menu • Panel
• ComboBox • PopUpMenu
• TextField • RadioButton
• Window • ScrollBar
• TextAres
Swing
Swing is the option by which we can use the java Graphics.
Swing provides the components which give the modern look
for the user interface, these components provide the toolkit.
The major components are labels, buttons, list controls, table
controls ect.
Swing is the one of the part of the Java Foundation Classes
(JFC). The JFC includes the rich graphics programming for
the Graphical User Interface.
There are various controls provided by the Swing which are as
follows
Image Buttons
Color choosers
List
Tables
Toolbars
HTML text areas
Trees
AWT & Swing
• Naming Convention : the components of the Swing
begins with capital letter J. There over 250 classes and
40 User Interface components which prebuilt in swing
package.
Example : JButton, JLabel,
• Lightweight Component : The graphics program of AWT
takes large number of windows which takes huge
memory. Such components are heavyweight.
• On other hand swing controls are simple drawn as
image in their containers and don’t have an operating
platform window of their own at all, so they use far
fewer system resources. Therefore they are called
lightweight components
AWT and its controls
• To develop GUI based applications, the fundamental elements
that are needed and are available in two packages java.awt
and javax.swing.
• The primary repository for class that we use to create GUI is
available in java.awt.
• Following are controls are supported by AWT or Swing .
• Label /JLabel
• Button / JButton
• TextField / JTextField
• CheckBox / JCheckBox
• RadioButtons / JRadioButton
• List / JList
• Combo Boxes – JCombo
• Menus – JMenu
• JMenuBar
• Scrollbars (JScrollBar)
• Dialogs
• JOptionPane
• JColorChooser
Label
Label class is used to create a Label control.
Label class is having following constructors
Label ()
Creates a blank label
Label (String)
Creates a label containing a specified string
in parameter.
Label (String, int)
Creates a label containing a specified string
with alignment which are specified in
second parameter.
The alignment must be one of the three constant values.
Label.LEFT
Label.RIGHT
Label.CENTER
Label
Methods
• void setText(String )
• Set or change the text in a label
• String getText()
• Obtain the text in a label
• void setAlignment(int)
• set or change the alignment of a text in a label
• Int getAlignment()
• Obtain the current alignment
Push Button :
• It is a component that contains a label and generates an event when it is
pressed.
• Button class is used to create push buttons. It has following constructors
• Button () -- > creates button with no label
• Button (String) -- > creates a button containing a specified string in
parameter.
• To create button in the AWT we perform the following steps
• Declare the button as variable
Button b1,b2,b3;
• Within frame creation method first we have to initialize the button by
dynamic.
b1 = new Button(“OK”);
b2 = new Button(“CANCEL”);
b3 = new Button(“Press Here”);
• Now we can add the labeled button to the frame with the add method.
add(b1);
add(b2);
• To make event with the button we must put them with ActionListener ( )
method as follows.
b1.addActionListener(this);
b2.addActionListener(this);
JButton :
• Swing Button provide features that are not found in
the Button class defined by the AWT
• That is we can associate an icon with a Swing
button.
• JButton class provides the functionality of a push
button.
• JButton allows an icon, a string or both to be
associated with the push button.
• Some of its constructors are
• JButton ( Icon i) ;
• JButton (String s);
• JButton (String s, Icon s);
• Here s and I are the String and icon respectively
used for the button.
• Example :
•
JButton
• JButton( ) Constructor
• Implements ActionListener
• JButton(Icon icon) • actionPerformed(ActionEvent e)
• JButton(String text)
Methods
• JButton(String text, Icon icon)
• void setText( String text)
• String getText( )
• void setIcon(Icon icon)
Methods
• Icon getIcon( )
• String getActionCommand( )
• void addActionListener( ActionListener al)
• void removeActionListener( ActionListener al)
• void setToolTipText( String text )
• String getToolTipText( )
TextField
• The TextField class implements a single – line text
entry, usually called an edit control.
• This TextField is subclass of the TextComponent
• The TextField uses the following components
• TextField tf1 = new TextField()
• TextField tf1 = new TextField(int numChars )
• TextField tf1 = new TextField(String str)
• TextField tf1 = new textField(String str, int
numChars)
• The TextField control had methods getText ( ) &
setText( String str) for getting and setting the
values.
void setEchoChar( char c)
char getEchoChar( )
JTextField
•The Swing text field (JTextField) is
encapsulated by the JTextComponent
class, which extends Jcomponent
•Constructors for the JTextField are as
•JTextField ( )
•JTextField (int cols)
•JTextField ( String s , int cols)
•JTextField (String s )
Example : ButtonTexFieldDemo
JTextField
• void setText( )
• String getText( )
• void setEditable ( boolean state)
• boolean isEditable( )
• void addActionListener(ActionListener al )
• void removeActionListener( ActionListener al)
Check Box :
• A Checkbox control is used to toggle an
option.
• It has following constructors
• Checkbox ( )
• creates check box without label. Initially
state is unchecked
• Checkbox (String)
• Creates a checkbox with label specified ,
initially state is unchecked
• Checkbox (String, boolean)
• checkbox with label and initial state is
specified either true or false in second
parameter.
Check Box
Methods
• boolean getState( ) :retries the current state
• void setState (boolean) : sets the state true/false
• String getLabel() : obtain the label associated
• void setLabel (String ) : set the label as specified.
• Checkbox getselectedCheckbox( );
• void setSelectedCheckbox(Checkbox which)
•Example : CheckBoxDemo.java
Check Box Group:
• This class is used to create group of checkboxes.
• From the group of check boxes only one check box be checked
at a time
• These check boxes are also called radio buttons
• It has following constructor
•CheckboxGroup CheckboxGroup()
returns group name
• Checkboxes of checkboxgroup can be created using following
constructors:
Implement interface:
ListSelectionListener( javax.swing.event )
Override method :
public valueChanged(ListSelectionEvent lse)
Register handler :
addListSelectionListener(ListSelectionListener lse)
Menu (JMenu)
• We can add AWT menus to Frame class windows using three
AWT classes Menubar , Menu, and MenuItem.
• The first class we use is the MenuBar class, which adds a
menu bar to a frame window.
• After we have added a menu bar to a frame window, we can
add menus, such as a File menu and Edit menu, to that menu
bar using Menu class.
• Finally, we add menu items to the menus in our program using
the MenuItem class.
• We create the individual menus in a MenuBar with the Menu
class.
• Constructors of the Menu class.
• Menu ( )
• Menu ( String lable)
• Menu (String lable, boolean tearOff)
• Example : MenuBarExample.java
• Example : PopUpMenu.java
JScrollPane
• This is the constructor of JScrollPane Class. It
extends from the JComponent. This constructor
uses to create a JScrollPane . This JScrollPane
displays the horizontal and vertical scroll bar. It
takes the components for which the scroll pane
has to be set.
Creating a JTabbedPane Container in
Java Swing
• JTabbedPane:
This is the class of javax.swing.*; package which creates the
JTabbedPane component of Java Swing which contains separate
button for the separate tab. You can also container component with
the specific tab.
• add():
This is the method of JTabbedPane class which is used to add
container component to the JTabbedPane component of Java Swing.
This method takes different-different types of arguments but in this
program this method has taken two argument, first is the title for the
tab and another is the component name which is specified for a
particular tab to show for that.
•
JComboBox
ComboBox is a drop – down list of items from which user can
select
• Class JComboBox is used to create combo box
• It generates ItemEvent Methods
• void addItem(Object Obj)
• Constructors • void insertItemAt(Object obj,int pos)
– JComboBox() • Object getItemAt(int pos)
– JComboBox(Object [] data) • Object getSelectedItem( )
– JComboBox(vector data) • void removeAllItems( )
• void removeItemAt(int pos)
• void removeItem(Object obj)
• int getItemCount( )
• void addActionListener
(ActionListener al)
• void addItemListener( ItemListener il)
•
JTextArea
A JTextArea is multi-line area that display pain text.
• It is lightweight component which is source compatible with
the java.awt.TextArea class
• Constructors Methods
– JTextArea( ) • void append( String str)
• void insert( String text, int pos)
– JTextArea(int rows,int cols)
• void replaceRange(String str ,int
– JTextArea(String text) start, int end)
– JTextArea(String text,int rs,int cs)
JOptionPane
• JOptionPane class makes it easy to pop up standard
dialog box that prompts users for a value or informs
them of something
• Static methods
– showConfirmDialog()
Asks a confirmaing question
– showInputDialog( )
Prompts for some input
– showMessageDialog( )
Tell the user about something that has happened.
• int showConfirmDialog(Component parentcomponent,
Object message,
String titel,
int optionType,
int messageType)
• int showInput Dialog(Component parentcomponent,
Object message,
String titel,
int optionType,
int messageType)
• int showMessageDialog(Component parentcomponent,
Object message,
String titel,
int optionType,
int messageType)
•
• MessageType
– ERROR_MESSAGE :used fro error messages
– INFORMATION_MESSAGE : used fro information messages
– QUESTION_MESSAGE : used for questions
• OptionType
– DEFAULT_OPTION
– YES_NOT_OPTION
– YES_NO_CANCEL_OPTION
– OK_CANCEL_OPTION
• When one of the method returns an integer, the possible values are
– YES_OPTION
– NO_OPTION
– CANCEL_OPTION
– OK_OPTION
– CLOSED_OPTION
Example
• JOptionPane.showMessageDialog(null,”alert”,”alert
”,JOptionPane.ERROR_MESSAGE)
• JOptionPane.showConfirmDialog(null,”choose one
”,JOptionPane.YES_NO_OPTION)
Layout Manager and Layouts
• For the arrangement of component within a container, Layout manger can be
used.
• A layout manager automatically arranges our controls within a window by
using some type of algorithm.
• Constructors:
• GridLayout()
• GridLayout(int rows,int cols)
• GridLayout(int rows,int cols,int hgap,int vgap)
BorderLayout
• Organizes the components along North, south, east and west borders and
in the center of container
• Only one object can be added on each region.
• To add a componet to specified region, the add method is used.
• The various constants in the BorderLayout manager are
• BorderLayout.NORTH
• BorderLayout.SOUTH
• BorderLayout.EAST
• BorderLayout.WEST
• BorderLayout.CENTER
• Constructors:
• BorderLayout()
• BorderLayout(int hgap,int vgap)
Syntax to add component:
add(Component obj,Object region)
• E.g
• add(button1, BorderLayout.NORTH)
CardLayout
• In this layout different cards are created and each
card is an object of type Panel.
• Components are placed in a card.
• The cards that form the deck are also an object of
the type Panel.
• Thus, we have to create a Penal that contains the
deck and Panel for each card in the deck.
• Then add these panels to the panel for which that
layout manager is CardLayout.
• After this add that Panel to the frame wndow.
• Constructors:
CardLayout()
CardLayout(int hagp,int vgap)
• Once a deck is created, we can activate a card by
calling one of the following methods of class
CardLayout:
void first( Deck) //Shows the first card in the deck.
void last( Deck) //Shows the last card in the deck.
void next( Deck) //Shows the next card in the deck.
void previous( Deck) //Shows the previous card in the deck.
void show( Deck,card) //Shows specific card.
Event Handling
• In GUI based application under windows, user actions such as pressing a
key, moving the mouse, selecting a menu item are first identified by the
operating system for each action, the operating system determines for which
program the action has been taken and passes.
• Ex. If user click a mouse button, operating systems registers this and
determines the position of the cursor. It than finds which application controls
the window and where the cursor was when you pressed the button and
communicates with signal to that program.
• The signal that program receives from the operating system as a result of
actions are called events.
• A program contains methods that handles the events. Such program is called
an event-driven program.
Java Method
User Operating
Library
System Method
Action Classes
Method
Following are important classes that represents events
• WindowEvent : Window is activated, closed, deactivated, iconified,
opened ect.
• MouseWheelListener :
void mouseWheelMoved (MouseWheelEvent e) : Mouse wheel is
moved
• KeyListener :
–void keyTyped (KeyEvent e) : when user presses a visible character key
• ItemListener :
–void itemStateChange (ItemEvent e) : when state of the item change
that is checked or unchecked checkbox , menu check item etc.
• TextListener :
–void textChanged (TextEvent e) : when state of the item change that is
checked or unchecked checkbox , menu check item etc.
• AdjustmentListener :
–void adjustmentValueChanged (AdjusmentEvent e) : when a scrollbar is
manipulated
• FocusListener :
–void focusGained (FocusEvent e) :
–void focusLost (FocusEvent e) :