0% found this document useful (0 votes)
44 views99 pages

Java Swing and Awt

A GUI presents a user-friendly interface for interacting with an application. GUIs use components like buttons and labels. Java provides AWT and Swing components, with Swing being lightweight and portable while AWT depends on native OS code. Common components include panels, containers, frames and dialogs.

Uploaded by

ktesfaneh2
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)
44 views99 pages

Java Swing and Awt

A GUI presents a user-friendly interface for interacting with an application. GUIs use components like buttons and labels. Java provides AWT and Swing components, with Swing being lightweight and portable while AWT depends on native OS code. Common components include panels, containers, frames and dialogs.

Uploaded by

ktesfaneh2
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/ 99

What is GUI(graphical user interface)?

 A graphical user interface (GUI) presents a user-friendly mechanism for


interacting with an application.

 GUIs are built from GUI components. These are sometimes called
controls or widgets.

 A GUI component is an object with which the user


interacts via the mouse, the keyboard or another form of input, such as
voice recognition.
Java Swing and AWT

• Java provides two sets of components for GUI programming:

 AWT: classes in the java.awt package

 Swing: classes in the javax.swing package


Abstract Windowing Toolkit (AWT):

 Sun's initial effort to create a set of cross-platform GUI classes. (JDK


1.0 - 1.1)

 Maps general Java code to each operating system's real GUI system.

Problems
 AWT components depend on native code counterparts to handle their
functionality. Thus, these components are often called heavyweight
components.
AWT cont...

• Component: A GUI widget that resides in a window.


 Also called controls in many other languages.
• Awt supports the following components:
 Labels
 Buttons
 Check boxes
 Choice lists
 Lists
 Scroll bars
 Text Editing
Swing

 Swing implements GUI components that build on AWT technology.

 Versions (JDK 1.2+)

 Swing is implemented entirely in Java.

 Swing components do not depend on operating system’s native code to


handle their functionality. Thus, these components are often called
lightweight components.

 Add J prefix to awt component


 Eg. JButton, Jlist, Jcheckbox…etc.
Swing: Pros and Cons

• Pros
− Portability: Pure Java implementation.
− Features: Not limited by native components.
− Look and Feel: Pluggable look and feel. Components automatically
have the look and feel of the OS they are running on.
• Cons
‒ Performance: Swing components handle their own painting (instead of
using APIs like DirectX on Windows).
‒ Look and Feel: May look slightly different than native components.
AWT: Pros and Cons

• Pros
‒ Speed: native components speed performance.
‒ Look and feel: AWT components more closely reflect the look and feel
of the OS they run on.
• Cons
‒ Portability: use of native peers(OS component) creates platform
specific limitations.
Components (Swing)
Components cont..
‒ Component is an abstract class that encapsulates all of the attributes of
a visual component.

‒ All user interface elements that are displayed on the screen and that
interact with the user are subclasses of Component.
Containers

‒ Is a subclass of Component(It is also an instance of a subclass of


java.awt.Container).
‒ Other Container objects can be stored inside of a Container.

‒ A container is responsible for laying out any components that it contains.

‒ Two Containers

 Window
Frame
dialog
 panel
Containers cont..

java.lang.Object java.awt.Component

java.awt.Container

javax.swing.JComponent
java.awt.Window
javax.swing.JPanel

javax.swing.JFileChooser
java.awt.Frame
javax.swing.JPopupMenu

javax.swing.JToolbar
javax.swing.JFrame
javax.swing.JLabel
Containers cont..

‒ Every container has a LayoutManager that determines how different components are
positioned within the container.

‒ Components are positioned inside the container according to a LayoutManager.


Containers cont..
‒ The AWT defines two different kinds of containers,
 Panels and
 Windows.
‒ Panels are subclasses of java.awt.Panel.
 A panel is contained inside another container.
 Panels do not stand on their own.
‒ Windows are subclasses of java.awt.Window.
 A window is a free-standing, native window.
Containers cont..
‒ There are two kinds of windows:
 Frames and
 Dialogs.
‒ A frame is an instance of a subclass of java.awt.Frame.
 It represents a normal, native window.
‒ A dialog is a subclass of java.awt.Dialog.
 A dialog is a transitory window that exists merely to impart some
information or get some input from the user.
Panel

‒ A Panel is a fairly generic Container whose primary purpose is to subdivide


the drawing area into separate rectangular pieces.

‒ Since each Panel can have its own LayoutManager, you can do many
things with panels that you can't do with a single LayoutManager.

‒ Panel is a window that does not contain a title bar, menu bar, or border.

‒ Other components can be added to a Panel object by its add( ) method


(inherited from Container).
Panel cont..
‒ If you want to add new Panel rather than the default one, use this syntax:
Panel panelName = new Panel();

then add any control you need to it using add() method:


panelName.add(controlObj);

finally add this panel to the default one by using add() method. i.e
add(panelName);

If you want to remove controls for panel:


remove(controlObj); // for single controls

removeAll(); // to remove all controls from the current panels.


Panel Example..
public class FrameDemo extends Frame{
public FrameDemo(){
Panel panel=new Panel();// creating new panel
panel.setLayout(new FlowLayout());
panel.setBackground(Color.red);
panel.add(new TextField(12));// adding comp to created panel
panel.add(new Button("Ok"));
this.add(panel); //adding created panel to default panel
}}
Windows
‒ The java.awt.Window class and its subclasses let you create free-standing
windows.

‒ A Window is a subclass of java.awt.Container that is independent of other


containers.
 Since Window extends java.awt.Container you can add components
like Buttons and TextFields to Windows.
Windows
‒ you Don't use the Window class directly. Instead you use one of its
subclasses, either java.awt.Frame or java.awt.Dialog depending on
your need.
‒ A Frame is what most people think of as a window in their native
environment.
• It can have a menu bar, titles, borders and resizing corners.
Windows cont..

‒ A Dialog will not have a menu bar.

 It can be moved.

 Its purpose is to get some particular information from the user (input) or to
impart some particularly important information to the user (output).
 It is normally visible on the screen only until it gets the input or receives
acknowledgement from the user about its output.
Windows cont..

‒ Frames are very useful in more complex applications.

‒ Frames let you separate different functions or data into different windows.

‒ Everything you need to create and work with frames is contained in the java.awt.Frame
class.
‒ To create a new frame without a title bar use the Frame() constructor with no arguments.

Frame f = new Frame();


‒ More commonly you'll want to name the frame so pass the constructor a string that
specifies the window's title.

Frame f = new Frame("My Window");


Windows cont..
‒ Unlike panels and applets, the default LayoutManager for a frame is
BorderLayout, not FlowLayout.
‒ However you can change this using the frame's setLayout() method like this:
f.setLayout(new FlowLayout());
‒ Frames inherit from java.awt.Component so they have paint() and update()
methods.
‒ If you want to draw in the frame and process events manually, just create a
subclass of Frame and add listener objects to it.
Frame cont..
‒ To add a component to a frame call the frame's add() method.
f.add(new Button("OK"));
‒ If you're calling add() from one of the Frame subclass's own methods you
won't need to do this.
this.add(new Button(“Ok”));
‒ Since the default layout for a frame is BorderLayout, you should specify
whether you want the component added to the North, South, East, West or
Center.
Frame cont..

‒ Here's how you'd add a centered label to the center of Frame f:


f.add("Center", new Label("frame")); or

f.add(new Label(“frame”),BorderLayout.CENTER);

‒ The size and position of any given frame is unpredictable unless you specify it.

‒ Specifying the size is easy. Just call the frame's setSize() method like this

f.setSize(150,150);
‒ You move a Frame with the setLocation(int x, int y) method.
 However x and y are relative to the screen
Frame cont..
‒ When you're done adding components, resizing and moving the Frame, make it
visible by calling its show() method like so:
Frame f=new Frame(“this is frame title”);
f.show();
or f.setVisible(true); //since it inherits from java.awt.Component
Frame Example
import java.awt.*;
public class FrameTester {
public static void main(String[] args) {
Frame myFrame = new Frame("My AWT Frame");
myFrame.setSize(250, 250);
myFrame.setLocation(300,200);
myFrame.add("Center", new Label(“Hello awt”));
myFrame.show();
}}
This window cannot be closed because it does not yet respond to the
WINDOW_CLOSING event.
Frame Example2
import javax.swing.*;
public class HelloWorldSwing {
public static void main(String[] args) {
JFrame frame = new JFrame("HelloWorldSwing");
final JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}

‒ JFrames (and Swing containers in general) differ from AWT frames (and AWT containers in
general) in that you must add component's to the JFrame's content pane rather than directly
to the frame itself. Furthermore JFrames are closeable by default whereas AWT frames are
not.
Centering a frame on screen

import java.awt.*;
public class CenteredFrameTester {
public static void main(String[] args) {
Frame myFrame = new Frame("My Frame");
myFrame.setSize(250, 250);
Toolkit kit = myFrame.getToolkit();
Dimension screenSize = kit.getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
Dimension windowSize = myFrame.getSize();
int windowWidth = windowSize.width;
int windowHeight = windowSize.height;
int upperLeftX = (screenWidth - windowWidth)/2;
int upperLeftY = (screenHeight - windowHeight)/2;
myFrame.setLocation(upperLeftX, upperLeftY);
myFrame.show();
} }
Main Steps in GUI Programming

‒ To make any graphic program work we must be able to create windows and add
content to them.

‒ To make this happen we must:

1.Import the awt or swing packages.


2.Set up a top-level container.
3.Fill the container with GUI components.
4.Install listeners for GUI Components.
5.Display the container.
Dialogs

‒ Dialogs are more transitory. They're used for simple user input or for quick alerts to the
user.
‒ java.awt.Dialog is a subclass of java.awt.Window and hence of java.awt.Container and
java.awt.Component.
‒ Therefore a lot of what you learned about frames applies to dialogs as well. You move
them, resize them and add to them almost exactly as you do for frames.
‒ There are two differences between dialogs and frames:

 A frame can have a menu bar. A dialog cannot.

 A dialog can be modal. A frame cannot.


Dialogs cont..

‒ A modal dialog blocks all other use of the application until the user
responds to it.
‒ A modal dialog cannot be moved and does not allow the user to switch to
another window in the same program.
 On some platforms the user may not even be able to switch to another
program
‒ Non-modal dialogs pop-up but they don't prevent the user from doing other
things while they're visible.
‒ Because modal dialogs inconvenience users by forcing them to respond
Dialogs cont..

‒ The only methods that are significantly different between a dialog and a frame are the
constructors.
‒ There are two constructors for Dialog which differ in whether or not the dialog is given a
title.

Dialog d = new Dialog(new Frame(), false);


‒ The second argument is a boolean which specifies whether or not the dialog should be
modal.
‒ Modal dialogs are only modal relative to their parent frame, which is passed as the first
argument to the constructor. That is they block input to the parent frame but not to other
frames.
Dialogs cont..
‒ You can make a dialog resizable and movable by calling its setResizable() method
with a boolean value of true like this:

d.setResizable(true);
‒ You can give a dialog a title bar by adding the title string to the constructor:

Dialog d = new Dialog(new Frame(), "My Dialog Window", false);


‒ All the other methods of the Dialog class are exactly the same as they are for
Frames.
Dialog Example
import java.awt.*;
public class DialogDemo {
public DialogDemo(){
Dialog d=new Dialog(new Frame(),"Title",false);
d.setSize(200,400);
d.add("South",new Button("Click Here"));
d.add("North",new TextField(23));
d.pack();
d.show(); }
public static void main(String arg[]){
new DialogDemo();
}}
Create your own Dialogs

‒ create your own dialog by extending it to Dialog class and instantiate that
subclass from the main program.
‒ For example one of the simpler common dialogs is a notification dialog that
gives the user a message to which they can say OK to signify that they've
read it. The next slide describes Dialog subclass.
Dialog subclass Example

create yoimport java.awt.*; public void actionPerformed(ActionEvent e)


import java.awt.event.*; {
public class DialogDemo extends Dialog implements ActionListener
{
this.setVisible(false);
public DialogDemo(Frame parent,String message){ this.dispose();
super(parent,message);
}
Panel panel=new Panel();
Button ok=new Button("Ok"); }
ok.addActionListener(this); class DialogCheck {
panel.setLayout(new FlowLayout()); public static void main(String s[]){
panel.add("Center",new Label("This is to Notify User using Dialog"));
DialogDemo demo=new
panel.add("South",ok);
DialogDemo(new Frame(),"Notification
this.add(panel);
Dialog Box");
this.pack();
this.setSize(200,100); demo.show();
this.setLocation(100,100); }
this.show(); }
}
Layout Manager

‒ All of the components that we have shown so far have been positioned
by the default layout manager.
‒ It is possible to lay out Java controls by hand, too, you generally won’t
want to, for two main reasons.
 First, it is very tedious to manually layout a large number of
components.
 Second, sometimes the width and height information is not yet
available when you need to arrange some control, because the
native toolkit components haven’t been realized.
Layout Manager cont..

‒ A layout manager is an instance of any class that implements the


Layout Manager interface. The layout manager is set by the
setLayout( )method.
‒ If no call to setLayout( )is made, then the default layout manager is
used. Theset Layout( )method has the following general form:
void setLayout(LayoutManagerlayoutObj)
‒ If you wish to disable the layout manager and position components
manually, pass null for layoutObj.
Layout Manager Type

‒ Flow Layout
‒ Grid Layout
‒ Border Layout
‒ GridBag Layout
‒ Card Layout
‒ Box Layout
Flow Layout
‒ FlowLayout is the default layout manager for panels.

‒ FlowLayout implements a simple layout style, which is similar to how


words flow in a text editor, which by default is left to right, top to bottom.
Therefore by default, components are laid out line-by-line beginning at
the upper-left corner.

‒ In all cases, when a line is filled, layout advances to the next line.
Flow Layout
‒ Here are the constructors for FlowLayout:
 FlowLayout( )
 FlowLayout(int how)
 FlowLayout(int how, int horz, int vert)
‒ Instantiate it this way
FlowLayout() flow=new FlowLayout();
flow.setAlignment(FlowLayout.CENTER);// in place of center you can also
use RIGHT,LEFT,LEADING AND TRAILING
flow.setHgap(5); // to set horizontal space between controls
flow.setVgap(10); // to set vertical space between controls
Flow Layout
‒ FlowLayout(int how) use it this way

FlowLayout flow=new FlowLayout(FlowLayout.LEFT); // for FlowLayout.LEFT


you can use 0 for left,1 for center 2 for right
‒ FlowLayout(int how,int hor, int ver) use it this way

FlowLayout flow=new FlowLayout(1,5,10);

In all case after you declare and intialize it provide it as argument to


setLayout() method.
i.e: setLayout(flow);
Border Layout

public BorderLayout()

‒ Divides container into five regions:


 NORTH and SOUTH regions expand to fill region horizontally,
and use the component's preferred size vertically.
 WEST and EAST regions expand to fill region vertically,
and use the component's preferred size horizontally.
 CENTER uses all space not occupied by others.

myFrame.setLayout(new BorderLayout());
myFrame.add(new JButton("Button 1"), BorderLayout.NORTH);

 This is the default layout for a JFrame.


Grid Layout

‒ GridLayoutlays out components in a two-dimensional grid. When you


instantiate a GridLayout, you define the number of rows and
columns.
‒ The constructors supported by GridLayout are shown here:
 GridLayout( )
Use it as GridLayout grid=new GridLayout();
grid.setRows(3); grid.setColumns(3); grid.setHgap(2);
grid.setVgap(3);
Grid Layout cont..

 GridLayout(intnumRows, intnumColumns)
Use it as GridLayout grid=new GridLayout(3,3);
 GridLayout(intnumRows, intnumColumns, inthorz, intvert)
Use it as GridLayout(3,3,10,5);
Finally add to SetLayout, using setLayout(grid);
Remember if want to add Layout to layout manager you can do it
as:
setLayout(new GridLayout(2,3,2,4)); // the same for flow and border
layout
Card Layout

‒ The CardLayout class is unique among the other layout managers in that it stores
several different layouts. Each layout can be thought of as being on a separate
index card in a deck that can be shuffled so that any card is on top at a given time.

‒ This can be useful for user interfaces with optional components that can be
dynamically enabled and disabled upon user input. CardLayout provides these
two constructors:
 CardLayout( )

 CardLayout(int horz, int vert)


Card Layout cont..

‒ Use of a card layout requires a bit more work than the other layouts. The
cards are typically held in an object of type Panel.

‒ This panel must have CardLayout selected as its layout manager. The
cards that form the deck are also typically objects of type Panel.

‒ Thus, you must create a panel that contains the deck and a panel for each
card in the deck. Next, you add to the appropriate panel the components
that form each card. Finally, you add this panel to the window.
Card Layout cont..

‒ When card panels are added to a panel, they are usually given a name. Thus,
most of the time, you will use this form of add( ) when adding cards to a panel:
 void add(ComponentpanelObj, Objectname)
Eg. Panel p=new Panel();
CardLayout c=new CardLayout(5,10);
p.setLayout(c);
Panel p1=new Panel();
Panel p2=new Panel();
p.add(p1,”Panel 1”);
p.add(p2,”Panel 2”);
add(p);
Card Layout cont..

‒ After you have created a deck, your program activates a card by calling
one of the following methods defined by CardLayout:
 void first(Container deck)

 void last(Container deck)

 void next(Container deck)

 void previous(Container deck)

 void show(Container deck, String cardName)


Card Layout cont..

‒ Here deck is a reference to the container (usually a panel) that holds the
cards, and cardName is the name of a card. Calling first( )causes the first
card in the deck to be shown.

‒ To show the last card, call last( ). The same for previous and next card. Both
next( )and previous( )automatically cycle back to the top or bottom of the
deck, respectively. The show( )method displays the card whose name is
passed in cardName.
Components
Components

‒ A component is an object having a graphical representation that can be


displayed on the screen. like checkboxes, menus, windows, buttons, text fields,
applets, and more.

‒ A container is a special component that can hold other components.

 Example of containers in typical GUI applications include:

panels, windows, applets, frames

‒ Functionality of most GUI components derive from the Component and


Container classes.
Component Elements
JLabel

‒ Label is the easiest control which is used to display string on screen. A


label is an object of type Label. Labels are passive controls that do not
support any interaction with the user(i.e It does not support any event
handler). Label defines the following constructors:

Label( )

Label(Stringstr)

Label(Stringstr, inthow)
JLabel cont..

‒ The first version creates a blank label. The second version creates a label

that contains the string specified by str. This string is left-justified.

‒ The third version creates a label that contains the string specified by str using

the alignment specified by how. The value of how must be one of these three

constants: Label.LEFT, Label.RIGHT, or Label.CENTER.

E.g. Label labelObj=new Label(“this is Label Demo”,Label.RIGHT);


JLabel cont..

‒ We can set or change the text in a label by using the setText( ) method.

‒ We can obtain the current label by calling getText( ).

void setText(String str)


String getText( )
‒ You can set the alignment of the string within the label by calling setAlignment( ).To
obtain the current alignment, call getAlignment( ).
JButton

‒ The most widely used control is button. button is a component that

contains a label and that generates an event when it is pressed. Buttons

are objects of type Button. Button defines two constructors:

 Button( )

 Button(String str)
JButton cont..

‒ For Button() use it this way:

 Button buttonObj=new Button();

 buttonObj.setLabel(“This is button Demo”); // setLabel() method

‒ For Button(String str) use it this Way

 Button buttonObj=new Button(“this is button Demo”);


JButton Example

import java.awt.*;
import javax.swing.*;

public class GuiExample1 {


public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 100));
frame.setTitle("A frame");

JButton button1 = new JButton();


button1.setText("Click me!");
button1.setBackground(Color.RED);
frame.add(button1);

frame.setVisible(true);
}
}
JButton cont..

Handling Buttons

‒ Each time a button is pressed, an action event is generated. This is sent to any

listeners that previously registered an interest in receiving action event notifications

from that component .

‒ Each listener implements the ActionListener interface. That interface defines the

actionPerformed( )method, which is called when an event occurs.

‒ An ActionEvent object is supplied as the argument to this method. It contains both a

reference to the button that generated the event and a reference to the action

command string associated with the button.


JButton cont..

‒ You can Add ActionListener to Button using two ways:


// the first way By Implementing the ActionListener Interface
button =new Button(“Demo”);
add(button);
button.addActionListener(this);
// do some actions
Public void actionPerformed(ActionEvent a){
If(a.getSource()==button){ /
/ what ever you want here
}
JButton cont..

‒ You can Add ActionListener to Button using the following ways as well.
• Import java.awt.event.ActionListener;
// import other class here us you program
• Public class ButtonDemo extends Applet {
• Button button;
• //other declaration here;
• Public void ButtonDemo(){
button =new Button(“Demo”);
add(button);
button.addActionListener(new ActionListener(){
• Public void actionPerformed(ActionEvent a){
• If(a.getSource()==button){ // what ever you want here }
Or if(a.getActionCommand().equals(“Demo”)){
}}}); //
}}
JButton cont..

‒ The label of a button is obtained by calling the getActionCommand( )method on

the ActionEvent object passed to actionPerformed( ).

‒ The Object of button is obtained by calling the getSource() method on the

actionevent object passed to actionPerformed() method.

‒ So to get Label of Button use this method.

a.getActionCommand().equals(“button”);

// to get Object of button

a.getSource()==button. // depending on the previous example


TextField
‒ The TextField class implements a single-line text-entry area, usually called an edit control.

‒ Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and

paste keys, and mouse selections. TextField is a subclass of TextComponent.

‒ TextField defines the following constructors:

 TextField( )

 TextField(intnumChars)

 TextField(Stringstr)

 TextField(Stringstr, intnumChars)
TextField

 TextField() use it this way:

TextField field=new TextField();

field.setColumns(15);// to limit number of character to

be displayed

field.setText(“Initial value of textfield”);


TextField
‒ TextField(int numChar) use it this way

TextField field=new TextField(15);

field.setText(“Initial value of textfield”);

‒ TextField(String str) use it this way

TextFeild field=new TextField(“initial value of textfield”);

‒ TextField(String str,int numChar) use this way

TextField field=new TextField(“initail value of textfield”, 15);

field.setEditable(true);// Editable textField, if false not editable

field.setEchoChar(‘@’); // to hide plain character of fields

field.select(2,6);// to select text start for index 2 upto index 6

field.getSelectedText(); // capture the selected text from the field


Handling Events
‒ Every time the user types a character or pushes a mouse button, an
event occurs.
‒ Any object can be notified of the event.
‒ All the object has to implement the appropriate interface and be
registered as an event listener on the appropriate event source.
How to Implement an Event Handler

‒ Every event handler requires three pieces of code:

1. declaration of the event handler class that implements a listener interface

or extends a class that implements a listener interface

public class MyClass implements ActionListener { ……}

2. registration of an instance of the event handler class as a listener

someComponent.addActionListener(instanceOfMyClass);

3. providing code that implements the methods in the listener interface in the

event handler class

public void actionPerformed(ActionEvent e) { ...//code that reacts to

the action...
How to Implement an Event Handler

1
public class ButtonClickExample extends JFrame implements ActionListener {

JButton b = new JButton("Click me!");

public ButtonClickExample() {

b.addActionListener(this); 2
getContentPane().add(b);

pack();

setVisible(true);

} 3
public void actionPerformed(ActionEvent e) {

b.setBackground(Color.CYAN);

public static void main(String[] args) {

new ButtonClickExample();
Text Field Event Handler

‒ Since text fields perform their own editing functions, your program

generally will not respond to individual key events that occur within a

text field. However, you may want to respond when the user presses

ENTER key. It uses ActionListener event handler


Text Area

‒ Sometimes a single line of text input is not enough for a given task. To

handle these situations, the AWT includes a simple multiline editor called

TextArea. Following are the constructors for TextArea:


 TextArea( )

 TextArea(int numLines, int numChars) // no of columns and char to be displayed

 TextArea(String str) // Initial value

 TextArea(String str, intnumLines, int numChars)

 TextArea(String str, intnumLines, int numChars, int sBars) // int sBars type of

Scrollbar, eg Scrollbar.VERTICAL, .HORIZONTAL,.VERTIVAL_ONLY and the like


Text Area cont..

‒ Most of the methods are similar to TextField but there is some new feature

for TextArea only.

void append(String str)

void insert(String str, int index)

void replaceRange(String str, int startIndex, int endIndex)

area.append(“this value”) // it add at the end index of the area but

setText() method replace the existing value on the area.

area.insert(3,6); // this insert new string starting from index 3 to index 6

area.replaceRange(“Replace”,3,12); // replace the existing text from 3 to


Checkbox

‒ A checkbox is a control that is used to turn an option on or off. It consists of a small


box that can either contain a check mark or not. There is a label associated with
each check box that describes what option the box represents.

‒ You change the state of a check box by clicking on it. Check boxes can be used
individually or as part of a group. Check boxes are objects of the Checkbox class.
 Checkbox( )

 Checkbox(String str)

 Checkbox(String str, boolean on)

 Checkbox(String str, boolean on, CheckboxGroup cbGroup) ,Checkbox(String


str, CheckboxGroup cbGroup, boolean on)
Checkbox cont..

‒ Checkbox() use it this way

Checkbox check=new Checkbox();

check.setLabel(“Default”); // to set Label of checkbox

check.setCheckboxGroup(cbGroupName);

check.setState(true); // checkbox created with checked state

‒ Checkbox(String str) use it this way

Checkbox check=new Checkbox(“LabelofCheckbox”); // with label

‒ Checkbox (String str,boolean on) use it this way

Checkbox check=new Checkbox(“Label”,true);// the state is on

‒ Checkbox(String str,boolean on, CheckboxGroup cbGroup) use it this way


Event handler for Checkbox

‒ Each time a check box is selected or deselected, an item event is generated. We can add
Item event to checkbox by implementing the ItemListener interface. That interface defines
the itemStateChanged( )method, with argument ItemEvent object.

‒ You can apply this ItemListener in similar way for actionListener.

‒ To execute any activities depending on checkbox state use getState() method. Like below:

Inside public void itemStateChanged(ItemEvent e) {

If(check.getState()==true/false){

//what ever you want to execute here

}
CheckboxGroup

‒ It is possible to create a set of mutually exclusive check boxes in which one and only one check
box in the group can be checked at any one time. These check boxes are often called radio
buttons.

‒ How to use CheckboxGroup

CheckboxGroup cbGroup=new CheckboxGroup();

Checkbox check=new Checkbox(“label”,cbGroup,true);

Checkbox check1=new Checkbox(“label”,cbGroup,true);

‒ You can determine which check box in a group is currently selected by calling
getSelectedCheckbox(). You can set a check box by calling setSelectedCheckbox().

 So depending on the above:

if(cbGroup.getSelectedCheckbox().getLabel()==check){ // operation to be executed here}


Choice Control
‒ The Choice class is used to create a pop-up list of items from which the user may choose. Thus, a
Choice control is a form of menu. When inactive, a Choice component takes up only enough space
to show the currently selected item. When the user clicks on it, the whole list of choices pops up,
and new selection can be made.

‒ Create Choice control using the default constructor i.e Choice().

Choice combobox=new Choice();

‒ To add item to it use add(String name) method;

combobox.add(“first”);

combobox.add(“second”);

‒ To determine which item is currently selected, you may call either getSelectedItem() or

getSelectedIndex().

‒ The getSelectedItem( )method returns a string containing the name of the item.
Choice cont…
 int getItemCount( ) // return number of item found in choice

 void select(int index) // select item whose index is supplied

 void select(String name) // select item whose label is supplied

 String getItem(int index) // capture item whose index is provided

Based on the previous slide

combobox.getItemCount(); // return 2

combobox.select(1); // second selected

combobox.select(first); // first selected

combobox.getItem(0); // return first


Event handler for Choice
 Use same Event handler as Checkbox.i.e itemListener interface

 To execute anything depending on the current selected item of choice

inside itemStateChanged() method or inside other applet method use this statements

If(combobox.getSelectedItem()==first){ // what ever here}

Or if(combobox.getSelectedIndex()==1){ // what ever here }

Or if (combobox .getItem(combobox.getSelectedIndex())==second){

// what ever here

}
List
‒ The List class provides a compact, multiple-choice, scrolling selection list. Unlike the
Choice object, which shows only the single selected item in the menu, a List object can
be constructed to show any number of choices in the visible window. List provides these
constructors:
 List( )

 List(int numRows) // limit item to be displayed

 List(int numRows, boolean multipleSelect) // decide single or multi selection

‒ To add item to List use add(string str) or add(string str, int index) methods.

‒ you can determine which item is currently selected by calling either getSelectedItem( )or
getSelectedIndex( ) for single selection.
List cont…
‒ you can determine which item is currently selected by calling either
getSelectedItems( )or getSelectedIndexes( ) for multiple selection.

‒ Event Handling in List


 To process list events, you will need to implement the ActionListener interface. Each
time a List item is double-clicked, an ActionEvent object is generated.
EventListeners
 To respond to an event, a component receives, you register an event listener for

the event type with the component.

 Event listeners are objects which implement a java.util.EventListener interface.


 The AWT defines eleven sub-interfaces of java.util.EventListener.

 java.awt.event.ComponentListener

 java.awt.event.ContainerListener

 java.awt.event.FocusListener

 java.awt.event.KeyListener

 java.awt.event.MouseListener

 java.awt.event.MouseMotionListener

 java.awt.event.WindowListener

 java.awt.event.ActionListener

 java.awt.event.AdjustmentListener
Mouse Events
 A java.awt.event.MouseEvent is sent to a component when the mouse state changes over the
component.

 There are seven types of mouse events, each represented by an integer constant:

 MouseEvent.MOUSE_CLICKED: A mouse button was pressed, then released


 MouseEvent.MOUSE_DRAGGED: The mouse was moved over the component while a
mouse button was held down
 MouseEvent.MOUSE_ENTERED: The cursor entered the component's space
 MouseEvent.MOUSE_EXITED: The cursor left the component's space
 MouseEvent.MOUSE_MOVED: The mouse moved in the component's space
 MouseEvent.MOUSE_PRESSED: The mouse button was pressed (but not released) over
the component

Mouse Events

 The main thing you want to know about a MouseEvent is the


location; that is, where the mouse was clicked.
 You can either request the x and y locations separately, or
together as a java.awt.Point object.
public int getX()
public int getY()
public Point getPoint()
Mouse Events
 Generally you respond to mouse events directed at your component, by
registering a MouseListener object with the component.
public interface MouseListener extends EventListener
 For reasons of efficiency, the MouseListener interface only declares five
methods:
public void mouseClicked(MouseEvent evt)
public void mousePressed(MouseEvent evt)
public void mouseReleased(MouseEvent evt)
public void mouseEntered(MouseEvent evt)
public void mouseExited(MouseEvent evt)
Key Events
‒ A java.awt.event.KeyEvent is sent to a component when a key is pressed while the
component has the focus.
‒ There are three types of key events:
 KeyEvent.KEY_PRESSED: A key was pressed
 KeyEvent.KEY_RELEASED: A key was released
 KeyEvent.KEY_TYPED: A key press followed by a key release.
‒ The main thing you want to know about a KeyEvent is what key was pressed. You
get this with the getKeyChar() method.
public char getKeyChar()
This returns the Unicode character corresponding to the pressed key.
Key cont’d…
‒ A KEY_PRESSED or KEY_RELEASED event doesn't just have a getKeyChar()
method. It has a getKeyCode() method.
‒ KEY_TYPED events do not have getKeyCode() method. It has getKeyChar()
method.
‒ If you're concerned about the key that was pressed, rather than the character that
was typed, you'll ask the key event for its key code rather than its key char.
‒ You get the code for a KeyEvent by calling getKeyCode():
public int getKeyCode()
Key cont’d…
‒ You can convert this into a localized string such as "END", "F4" or "Q" by passing it to
the static method, KeyEvent.getKeyText():
public static String getKeyText(int keyCode)
‒ Generally you respond to key events directed at your component, by registering a
KeyListener object with the component.
‒ The KeyListener interface defines the following methods, one for each type of
KeyEvent.
public void keyTyped(KeyEvent evt)
public void keyPressed(KeyEvent evt)
public void keyReleased(KeyEvent evt)
Adapter Classes
‒ The AWT provides a number of adapter classes for the different EventListener
interfaces. These are:

ComponentAdapter

ContainerAdapter

FocusAdapter

KeyAdapter

MouseAdapter

MouseMotionAdapter

WindowAdapter
Adapter Classes
‒ Therefore, MouseAdapter can be written as:
package java.awt.event;
import java.awt.*;
import java.awt.event.*;
public class MouseAdapter implements MouseListener {
public void mouseClicked(MouseEvent evt) {}
public void mousePressed(MouseEvent evt) {}
public void mouseReleased(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}}

By subclassing MouseAdapter rather than implementing MouseListener directly, you avoid


having to write the methods you don't actually need. You only override those that you plan to
actually implement.
Example:

import java.awt.*;
import java.awt.event.*;
public class MouseBeeper extends MouseAdapter {
public void mouseClicked(MouseEvent evt) {
Toolkit.getDefaultToolkit().beep();
// No need to write other left unimplemented method of mouselisetner
interface. Since MouseAdapter class does the job.
}
}
Menu
‒ Menus are composed of three hierarchical pieces.
 MenuBar, Menu and MenuItem
‒ The menu bar contains the various menus.
 Each menu bar contains one or more menus. Menus are organized topically.
‒ Each menu contains one or more menu items.
‒ The menu items are the individual actions such as Open, Print, Cut or Copy.
 They are not shown except when the menu is active.
‒ No more than one menu will be active at a time.
Menu Classes
‒ The AWT contains four main classes to handle menus:
java.awt.Menu
java.awt.MenuBar
java.awt.MenuItem
java.awt.PopupMenu

‒ To use menus in your application you need to add instances of all three
classes,
 one MenuBar with one or more Menus, each with several MenuItems.
Menu Classes
‒ The java.awt.MenuComponent class is the ultimate superclass of all
these classes.
• MenuComponent extends java.lang.Object.
‒ Thus menus, menu bars, and menu items are not components and
cannot be added to containers in the usual fashion.
‒ Both MenuBar and MenuItem extend MenuComponent.
‒ Menu extends MenuItem.
‒ Furthermore, MenuBar implements the java.awt.MenuContainer
interface.
Menu Classes
‒ Swing contains three main classes to handle menus:
javax.swing.JMenu
javax.swing.JMenuBar
javax.swing.JMenuItem
javax.swing.JCheckboxMenuItem
javax.swing.JRadioButtonMenuItem
‒ MenuBar implements the java.awt.MenuContainer interface.
Steps to Create Menu
‒ You should build the menus before you display them. The typical order is:

Create a new MenuBar.

Create a new Menu.

Add items to the Menu.

Add the Menu to the MenuBar.

If necessary repeat steps 2 through 4.

Add the MenuBar to the Frame.


‒ The constructors you need are all simple. To create a new MenuBar object:
MenuBar myMenubar = new MenuBar();
Create Menu
‒ To create a new Menu pass it the title of the menu you want.
‒ For example, to create File and Edit menus,
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
‒ MenuItems are created similarly by passing it the title of the menuitem you want:
MenuItem cut = new MenuItem("Cut");
‒ You can create MenuItems inside the Menus they belong to.
fileMenu.add(new MenuItem(“Cut”));
Create Menu
‒ Menu's have add methods that take an instance of MenuItem. Here's how you'd build an Edit Menu complete with Undo, Cut, and Copy

MenuItems:

Menu editMenu = new Menu("Edit");

MenuItem undo = new MenuItem("Undo")

editMenu.add(undo);

editMenu.addSeparator();

MenuItem cut = new MenuItem("Cut")

editMenu.add(cut);

MenuItem copy = new MenuItem("Copy")

editMenu.add(copy);

‒ The addSeparator() method adds a horizontal line across the menu. It's used to separate logically separate functions in one menu.
Create Menu

‒ Once you've created the Menus, you add them to the MenuBar using the MenuBar's add(Menu m) method like

this:

myMenubar.add(fileMenu);

myMenubar.add(editMenu);

‒ Finally when the MenuBar is fully loaded, you add the Menu to a Frame using the frame's setMenuBar(MenuBar

mb) method.

 Given a Frame f:

f.setMenuBar(myMenuBar);

MenuItem copy = new MenuItem("Copy")

editMenu.add(copy);

You might also like