aaaa Java UNIT-1
aaaa Java UNIT-1
Component class
Component class is at the top of AWT hierarchy. It is an abstract class that
encapsulates all the attributes of visual component. A component object is
responsible for remembering the current foreground and background colors and
the currently selected text font.
Containers
Container in Java AWT is a component that is used to hold other components
such as text fields, buttons, etc. It is a subclass of java.awt.Component and is
responsible for keeping a track of components being added. There are four types
of containers provided by AWT in Java.
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
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
Panel is the concrete subclass of Container and doesn’t contain any title bar,
menu bar or border 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.
There are two ways to create a Frame.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
=================================================
1. By extending Frame class (inheritance)
import java.awt.*;
import java.awt.event.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30); // setting button position
add(b); //adding button into frame
setSize(300,300); //frame size 300 width and 300 height
setLayout(null); //no layout now bydefaultBorderLayout
setVisible(true); //now frame willbe visible, bydefault not visible
}
public static void main(String args[])
{
First f=new First();
}
}
===================================================================
==
2. By creating the object of Frame class (association)
EX-1
import java.awt.*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame(); //Creating a frame
Label lb = new Label("welcome to java graphics"); //Creating a label
fm.add(lb); //adding label to the frame
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}
===================================================================
EX-2
===================================================================
=====
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on
button, dragging mouse etc. The java.awt.event package provides many event
classes and Listener interfaces for event handling.
Java Event classes and Listener interfaces
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Steps to perform Event Handling
Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
Java Event Handling Code
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
Java event handling by implementing ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener
{
TextField tf;
AEvent()
{
tf=new TextField(); //create components
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibili
ty
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been used
in the above example that sets the position of the component it may be button,
textfield etc.
Skip Ad
=============================================================
3) Java event handling by anonymous class
import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame
{
TextFieldtf;
AEvent3()
{
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}
===================================================================
=
Java AWT Label
The object of the Label class is a component for placing text in a container. It is
used to display a single line of read only text. The text can be changed by a
programmer but a user cannot edit it directly.
It is called a passive control as it does not create any event when it is accessed. To
create a label, we need to create the object of Label class.
AWT Label Class Declaration
1. public class Label extends Component implements Accessible
AWT Label Fields
The java.awt.Component class has following fields:
1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.
Label class Constructors
Sr. no. Constructor Description
1. Label() It constructs an empty label.
2. Label(String It constructs a label with the given string (left justified
text) by default).
3. Label(String It constructs a label with the specified string and the
text, int specified alignment.
alignement)
Label Class Methods
Sr. no. Method name Description
1. void setText(String It sets the texts for label with the specified text.
text)
2. Void setAlignment It sets the alignment for label with the specified
(int alignment) alignment.
3. String getText() It gets the text of the label
4. int getAlignment() It gets the current alignment of the label.
5. void addNotify() It creates the peer for the label.
6. AccessibleContext It gets the Accessible Context associated with
getAccessibleContext( the label.
)
7. protected String It returns the string the state of the label.
paramString()
Method inherited
The above methods are inherited by the following classes:
o java.awt.Component
o java.lang.Object
Java AWT Label Example
In the following example, we are creating two labels l1 and l2 using the
Label(String text) constructor and adding them into the frame.
LabelExample.java
import java.awt.*;
public class LabelExample
{
public static void main(String args[]){
// creating the object of Frame class and Label class
Frame f = new Frame ("Label example");
Label l1, l2;
l1 = new Label ("First Label."); // initializing the labels
l2 = new Label ("Second Label.");
l1.setBounds(50, 100, 100, 30); // set the location of label
l2.setBounds(50, 150, 100, 30);
f.add(l1); // adding labels to the frame
f.add(l2);
f.setSize(400,400); // setting size, layout and visibility of frame
f.setLayout(null);
f.setVisible(true);
}
}
c.getItem(c.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String args[])
{
new ChoiceExample2();
}
}
Java AWT List
The object of List class represents a list of text items. With the help of the List
class, user can choose either one item or multiple items. It inherits the
Component class.
AWT List class Declaration
public class List extends Component implements ItemSelectable, Accessible
AWT List Class Constructors
Sr. Constructor Description
no.
1. List() It constructs a new scrolling list.
2. List(int row_num) It constructs a new scrolling list initialized
with the given number of rows visible.
3. List(int row_num, It constructs a new scrolling list initialized
Boolean multipleMode) which displays the given number of rows.
Methods Inherited by the List Class
The List class methods are inherited by following classes:
o java.awt.Component
o java.lang.Object
// importing awt and event class
import java.awt.*;
import java.awt.event.*;
public class ListExample2
{
ListExample2() { // class constructor
Frame f = new Frame(); // creating the frame
final Label label = new Label(); // creating the label which is final
label.setAlignment(Label.CENTER); // setting alignment and size of label
label.setSize(500, 100);
Button b = new Button("Show"); // creating a button
b.setBounds(200, 150, 80, 30); // setting location of button
final List l1 = new List(4, false); // creating the 2 list objects of 4 rows
l1.setBounds(100, 100, 70, 70); // setting location of list components
l1.add("C"); // adding items to the list using add()
l1.add("C++");
l1.add("Java");
l1.add("PHP");
final List l2=new List(4, true);
l2.setBounds(100, 200, 70, 70);
l2.add("Turbo C++");
l2.add("Spring");
l2.add("Hibernate");
l2.add("CodeIgniter");
f.add(l1); // adding List, Label and Button to the frame
f.add(l2);
f.add(label);
f.add(b);
f.setSize(450,450); // setting size, layout and visibility of frame
f.setLayout(null);
f.setVisible(true);
// generating event on the button
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String data = "Programming language Selected:
"+l1.getItem(l1.getSelectedIndex());
data += ", Framework Selected:";
for(String frame:l2.getSelectedItems())
{ data += frame + " ";
}
label.setText(data);
}
});
}
public static void main(String args[])
{
new ListExample2();
}
}
{
new ScrollbarExample2();
}
}
==============================================================
AWT Menu Class
A menu bar can be created using MenuBar class.
A menu bar may contain one or multiple menus, and these menus are
created using Menu class.
A menu may contain one of multiple menu items and these menu items are
created using MenuItem class.
import java.awt.*;
class MenuExample
{
MenuExample()
{
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}
// Java program to create a menubar and add menuitems to it and also add menu
shortcut to MenuItems
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Shortcut_1 extends
Frame implements ActionListener {
static MenuBar menubar; // menubar
static Menu menu; // Menu
static MenuItem menuitem_1, menuitem_2, menuitem_3; // Menu items
static Frame frame; // create a frame
Label label; // create label
Shortcut_1() // default constructor
{
frame = new Frame("MenuShortcut Demo"); // create a
frame
// when exit button is pressed
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent)
{
System.exit(0);
}
});
menubar = new MenuBar(); // create a menubar
menu = new Menu("Menu"); // create a menu
label = new Label("Nothing Selected"); // create label
// create menu shortcuts
MenuShortcut menushortcut_1 =
new MenuShortcut(KeyEvent.VK_A, false);
MenuShortcut menushortcut_2 =
new MenuShortcut(KeyEvent.VK_B, false);
MenuShortcut menushortcut_3 =
new MenuShortcut(KeyEvent.VK_C, false);
// create menuitems
menuitem_1 = new MenuItem("MenuItem_1 ", menushortcut_1);
menuitem_2 = new MenuItem("MenuItem_2 ", menushortcut_2);
menuitem_3 = new MenuItem("MenuItem_3 ", menushortcut_3);
// add ActionListener to menuItems
menuitem_1.addActionListener(this);
menuitem_2.addActionListener(this);
menuitem_3.addActionListener(this);
menu.add(menuitem_1); // add menu items to menu
menu.add(menuitem_2);
menu.add(menuitem_3);
menubar.add(menu); // add menu to menu bar
frame.setMenuBar(menubar); // add menubar to frame
frame.add(label); // add label
frame.setSize(500, 500); // set the size of the frame
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) // when an action is performed
{
String s = e.getActionCommand();
label.setText(s + " selected"); // set the label to the menuItem that is
selected
}
public static void main(String args[]) // Main Method
{
Shortcut_1 m = new Shortcut_1(); // create an object
}
}
=================================================================
Java AWT Panel:
The Panel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the Container class.
It doesn't have title bar.
AWT Panel class declaration
public class Panel extends Container implements Accessible
import java.awt.*;
public class PanelExample
{
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Java AWT Dialog:
The Dialog control represents a top level window with a border and a title used to
take some form of input from the user. It inherits the Window class. Unlike
Frame, it doesn't have maximize and minimize buttons.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize
buttons but Dialog doesn't have.
AWT Dialog class declaration
public class Dialog extends Window
Java AWT Dialog Example
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
==============================END===============================