Unit Ii
Unit Ii
Component
Window
o Window is also a sub class of a container.
o Window class creates a top level window. A top-level window is not contained within
any other object, it sits directly on the desktop.
o We won’t create window object directly. We can use a subclass of window called
Frame.
Frames
o Frame Class is also a sub class of window class.
o Frame Class provides a Special Type of Window which has a title bar, menu bar,
borders and resizing corners.
o It is a container that contains several different components like button, title bar,
textfield, label etc.
Ans:
The methods of Component class are widely used in java swing that are given below:
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.
FRAME in AWT
Que:
1. Write code to create FRAME WINDOW in Applet.
2. How to create a Frame window within an applet? Give an example.
3. How to create a frame window in applet?
4. Define Frame and state two ways to create a frame.
5. Explain the process of creating a frame and adding a button to it.
Ans:
Steps to create a new frame window from within an applet are shown below:
Example:
The following applet creates a subclass of Frame called SampleFrame.
A window of this subclass is instantiated within the init( ) method of AppletFrame.
This example overrides the applet's start( ) and stop( ) methods so that they
show and hide the child window, respectively.
This causes the window to be removed automatically when you terminate the applet,
when you close the window, or, if using a browser, when you move to another page.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AppletFrame" width=300 height=50>
</applet>
*/
SampleFrame(String title) {
super(title);
addWindowListener(adapter);
}
SampleFrame sampleFrame;
import java.awt.*;
SimpleExample(){
b.setBounds(50,50,50,50);
add(b);
setSize(500,300);
setLayout(new FlowLayout());
setVisible(true);
}
import java.awt.*;
Example2()
{
fr.add(lb);
fr.add(t);
fr.setSize(500, 300);
fr.setLayout(new FlowLayout());
fr.setVisible(true);
}
public static void main(String args[])
{
Example2 ex = new Example2();
}
}
Output:
PANEL in AWT
Que:
1. Explain panel in java with example.
Ans:
It is a window that does not have a title bar, menu bar or border.
Example:
import java.awt.*;
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
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();
}
}
CANVAS in AWT
Que:
1. Explain Canvas class with example.
2. What is CANVAS in AWT? List its Constructors & Methods.
Ans:
Constructors of Canvas
Name Description
Canvas() This constructor creates instance of a Canvas.
Canvas(GraphicsConfiguration This constructor creates instance of a Canvas with the given
config) object of Graphics Configuration.
Methods of Canvas
Method Description
Paint(Graphics g) Paint the Canvas.
Update(Graphics g) Update the Canvas.
Example:
import java.awt.*;
import java.applet.*;
public class cn extends Applet
{
public void init()
{
MyCanvas c=new MyCanvas();
c.setVisible(true);
add(c);
}
}
class MyCanvas extends Canvas
{
public MyCanvas ()
{
setBackground (Color.GRAY);
setSize(300, 300);
}
Label
Constructors:
Name Action
Label() Create an empty label.
Label(String) Creates a label initialized with the given string, and aligned left.
Label(String, int) Creates a label with specified text and alignment indicated by the int
argument: Label.LEFT, Label.RIGHT, and Label.CENTER
Methods :
Name Action
int getAlignment() Retrieves a label's alignment setting.
String getText() Retrieves a label's test string.
void setAlignment(int align) Sets the alignment for this label to the specified
alignment. Possible values are Label.LEFT,
Label.RIGHT, and Label.CENTER
void setText(String label) Sets a label's text string.
Example:
Import java.awt.*;
Import java.applet.*;
/*
<applet code="LabelDemo" width=300 height=200>
</applet>
*/
public class LabelDemo extends Applet
{
public void init()
{
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
add(one);
add(two);
add(three);
}
}
Output:-
TextField
It is useful for obtaining information from users. It considers only single line input.
constructor Action
TextField( ) Creates an empty TextField that is 0 characters wide (it will
be resized by the current layout manager).
TextField(int) Creates an empty text field. The integer argument indicates the
minimum number of characters to display.
TextField(String) Creates a text field initialized with the given string.
TextField(String, int) Create a new textfield initialized with the specified text to be
displayed,and wide enough to hold the specified number of
columns.
Methods:
Constructor Action
String getText( ) Returns the text this text field contains (as a string)
Void setText(String) Puts the given text string into the field
int getColumns( ) Returns the width of this text field.
String select(int, int) Selects the text between the two integer positions (positions start
from 0)
Void selectAlI( ) Selects all the text in the field
Boolean isEditable( ) Returns true or false based on whether the text is editable
Void setEditable(boolean) true (the default) enables text to be edited; false freezes the text
Char getEchoChar( ) Returns the character used for masking input
Boolean echoCharIsSet() Returns true or false based on whether the field has a masking
character
Example:
Import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="TextFieldDemo" width=380 height=150>
</applet>
*/
output:-
TextArea
Constructors:
Name Action
TextArea( ) Creates an empty text area 0 rows long and 0 character wide (the
text area will be automatically resized based on the layout manager).
TextArea(int, int) Creates an empty text area with the given number of rows and
columns (characters)
TextArea(String) Creates a text area displaying the given string, which will be sized
according to the current layout manager.
TextArea(String, int, int) Creates a text area displaying the given string and with the given
dimensions
Methods :
Name Action
int getColumns() Returns the width of the text area, In characters or columns
int getRowsO Returns the number of rows in the text area
void insertText(String, Inserts the string at the given position in the text (text positions start
int) at 0).
void replaceText(String, Replaces the text between the given integer positions with the new
int, int) string
Example:
import java.awt.*;
import java.applet.*;
/*
<applet code="TextAreaDemo.class" width=300 height=250>
</applet>
*/
public class TextAreaDemo extends Applet {
Output:
Buttons
The most widely used control is the push button. A push button is a component that contains a label
and that generates an event when it is pressed.
Push buttons are objects of type Button.
Constructors
Name Action
Button( ) Creates an empty button with no label
Button(String) Creates a button with the given string object as a label.
Methods
Name Action
String getLabel( ) Get the label of this Button instance
Void setLabel(string) Set the label of this Button instance
Void setEnable(boolean) Enable or disable this Button. Disabled Button cannot be
Clicked.
Example:
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=250 height=150>
</applet>
*/
}
}
Output:
Check Boxes
A check box 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.
Constructors:
Name Action
Checkbox( ) Creates a check box whose label is initially blank. The state
of the check box is unchecked.
1. Checkbox(String str) Creates a checkbox whose label is specified by str.
2. Checkbox(String str, boolean on) Allows you to set the initial state of the check box. If on is
true, the check box is initially checked otherwise, it is
cleared.
Methods:
Name Action
Boolean getState( ) Returns true or false, based on whether the check box is
selected
1. Void setState(Boolean on) Change state of checkbox selected or unselected.
2. String getLabel( ) Returns a string containing this check box's label
3. void setLabel(String str) Changes the text of the check box's label
4. void Used to add checkbox into checkboxGroup.
setCheckboxGroup(CheckboxGroup)
.
Example:
importjava.awt.*;
importjava.applet.*;
/*
<applet code="CheckboxDemo" width=250 height=200>
</applet>
*/
public class CheckboxDemo extends Applet
{
String msg = "";
Checkbox Win98, winNT, solaris, mac;
add(Win98);
add(winNT);
add(solaris);
add(mac);
}
public void paint(Graphics g)
{
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows 98/XP: " + Win98.getState();
g.drawString(msg, 6, 100);
msg = " Windows NT/2000: " + winNT.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " MacOS: " + mac.getState();
g.drawString(msg, 6, 160);
}
}
Output:-
CheckboxGroup
Constructor
Name Action
CheckboxGroup( ) Create a new instance of the CheckboxGroup .
Methods
Name Action
getSelectedCheckbox() Returns the current choice from the check box group.
setSelectedCheckbox(Checkbox Itis used to make one of the box selected among all the
box) check boxes.
Example:
importjava.awt.*;
importjava.awt. *;
import java. applet.Applet;
output
Constructor:
Name Action
Choice() Creates a new choice List.
Methods:
Name Action
add(String text) Add an item to the choice list.
getItem(int index) Returns the string at the specified index from the Choice list.
getItemCount() Returns the number of items in the choice list.
getSelectedIndex() Return the index of the currently selected item.
getSelectedItem() Returns the currently selected item as a string.
insert(String item, int index) Inserts the item into the choice list at the specified position.
remove(int position) Removes an item from the choice list at the specified position.
remove(String item) Removes the first occurrence of item from the Choice list.
removeAll() Removes all items from the choice list.
select(int) Selects the item at the given position.
select(String) Selects the item with the given string.
Example:
/*ChoiceListDemo.java */
importjava.awt.*;
importjava.awt. *;
import java. applet.Applet;
c.addItem("Apples");
c.addI tem("Orange s");
c.addItem("Suawberries");
c.addItem("Blueberries");
c.addItem("Bananas");
add(c);
}
}
List
The List component is a scrolling list of strings from which one or more strings can be selected.
The List class is use for creating single- and multiple-selection list.
Constructor:
Name Action
List( ) Creates an empty scrolling list that enables only one selection
at a time.
List(int, boolean) Creates a scrolling list with the given number of visible lines on the
screen. The boolean indicates whether this list enables multiple
selections (true) or not (false).
Methods
Name Action
Void addItem(String ) Used to build the scrolling list
String getItem(int) Returns the string item at the given position.
int Countltems() Returns the number of items in the menu
Int getSelectedIndex( ) Returns the index position of the item that's selected (used for
lists that allow only single selections)
String[ ] getSelectedItems( ) returns an array containing the names of the currently selected
items
1. int[ ] getSelectedIndexes( ) returns an array containing the indexes of the currently selected
items.
2. select(int) Selects item at specified index.
3. Select(string) Selects item with that string.
/*ScrollingListDemo.java */
import java.awt.*;
importjava.awt.*;
import java.app1et.App1et;
public class ScrollingListDemo extends App1et
{
public void init() {
List 1st = new List(5, true);
1st.addItem("CDR");
1st.addItem("CDRW");
Ist.addItem("DVD");
1st.addItem("PenDrive");
1st.addI tem("Zipdrive");
lst.addltem("RO M");
add(lst);
}
}
Output:
Sample output is shown below:-
Layout Managers
Que:
1. Differentiate border layout and flow layout.
2. List out types of Layout Manager. Explain flow layout manager with example.
3. Explain Border Layout with example.
4. Explain Flow Layout with example.
5. List layout manager classes in Java.
6. List out Layout Manager.
7. List and explain different layout managers in Java.
8. ________ Layout manager lays out the components from left to right.
9. Explain any one with example.
10. List of layout managers in java
11. Explain grid layout manager in Java.
Ans:
The LayoutManagers are used to arrange components in particular manner.
LayoutManager is an interface that is implemented by all the classes of layout managers.
The layout manager set by the SetLayout() method. If we don’t use this method then default
layout manager is used.
The setLayout( ) method has the following general form:
Void setLayout(LayoutManager layoutObj)
Here, layoutObj is a reference to the desired layout manager.
If you wish to disable the layout manager and position components manually, pass null for layoutObj.
If you do this, you will need to determine the shape and position of each component manually, using
the setBounds( ) method defined by Component.
FlowLayout
FlowLayout is a simple layout manager that arrange components from upper-left corner, left to right
and top to bottom.
FlowLayout is the default layout for panel and applet.
By default, a flow layout uses CENTER justification, meaning that all components are centered within
the area allotted to them.
Constructors:
Constructor Description
creates the default layout, which centers components and leaves five
FlowLayout()
pixels of space between each component.
Specify how each line is aligned. Valid values for how are:
FlowLayout(int how)
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout(int how,int Create a flowlayout with the given alignment and given horizontal and
horz, int vert) vertical gap.
Example:
Import java.awt.*;
BorderLayout
The BorderLayout is used to arrange the components in five regions: north,south,east,west and center.
Constructors:
Constructor Description
BorderLayout() Creates a border layout with no space between the components.
BorderLayout(int horz, int Creates a border layout with the given horizontal and vertical
vert) space between the components.
Example:
import java.awt.*;
Grid Layout
As the name indicates the container is divided into a grid of cells formed by rows and columns.
Each cell hold one component.
Components added to the container with the GridLayout manager are arranged in order from left to
right.
Constructors of GridLayout
Constructor Description
Creates a gridlayout with one column per component in a
GridLayout ()
row.
Creates a gridlayout with the given rows and columns but
GridLayout (int rows, int columns) no space between the components.
GridLayout(int rows,int columns,int Creates a gridlayout with the given rows and columns
horz, int vert) along with given horizontal and vertical space.
Example
public class GridLayoutDemo extends Applet {
static final int n = 4;
CardLayout
Constructor:
Constructor Description
CardLayout() Creates a card layout with zero horizontal and vertical space.
CardLayout(int horz,int vert) Creates a card layout with the given horizontal and vertical space.
Methods
Name Description
void first(Container a) It is used to flip to the first card of the given container.
void last(Container a) It is used to flip to the last card of the given container.
void next(Container a) It is used to flip to the next card of the given container.
void previous(Container a) It is used to flip to the previous card of the given container.
void show(Container a, String
It is used to flip to the specified card with the given name.
cardName)
‘a’ is a reference to the container(usually a panel) that holds the cards, and cardName
is the name of a card.
Example:
import java.awt.*;
import java.awt.event.*;
c=getContentPane();
card=new CardLayout(40,30);
c.setLayout(card);
b1=new Button("Apple");
b2=new Button("Boy");
b3=new Button("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);
c.add("b",b2);
c.add("c",b3);
}
public void actionPerformed(ActionEvent e) {
card.next(c);
}
Benefits of LayoutManager:
Not necessary to compute the coordinates at which component is to be placed.
If the Applets output frame is re-sized dynamically adjusts placement of components
Que:
1. Explain event handling in Java.
2. Explain event delegation model.
3. List out Interfaces of Event Listener.
4. List any five Event classes and five Listener interfaces in JAVA.
5. Event Class
6. Explain event listeners in JAVA.
7. List out types of Event classes.
Ans:
Event Handling: It is the mechanism that controls the event and decides what should happen if an
event occurs.
Modern approach to handle events is based on the Delegation Event Model.
In event delegation model, a source generates an event and sends it to one or more listeners.
In this scheme, the listener simply waits until it receives an event. Once received, the listener
processes the event and then returns.
In the delegation event model, listeners must register with a source in order to receive an event
notification.
The Event Delegation model is based on – The Event, Event Source and Event Listener.
Events
An event is a change of state of an object.
When the user interacts with a GUI application, an event is generated.
Example: Pressing a button, Entering a character in Textbox., selecting an item or closing a
window.
Event object is used to carry the required information about the state change.
Event Sources
A source is an object that generates an event. Sources may generate more than one type of event.
A source must register listeners in order for the listeners to receive notifications about a specific type
of event.
Each type of event has its own registration method. Here is the general form:
public void addTypeListener(TypeListener el)
Here, Type is the name of the event and el is a reference to the event listener.
Event Listeners
Event Classes
At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass
for all events.
Constructor:
EventObject(Object src)
Here, src is the object that generates this event.
Methods:
1. object getSource(): It returns the object that originated the event. So if the user has clicked a
Push button, the method getSource returns the object corresponding to Push button is generated.
2. int getID(): This method returns the integer value corresponding to the type of event. For
example, if the user has clicked on the mouse, the method getID returns the integer defined as
MouseEvent.
Events are supported by a number of Java packages, like java.util,java.awt and java.awt.event.
MouseEvent :
A MouseEvent is fired to all its registered listeners, when you press or release a mouse-button at the
source. object position the mouse-pointer at (enter) and away (exit) from the source object.
Methods:
getPoint( ) - Returns a Point object that contains the x and y coordinates. The point is where the
event occurred.
getClickCount() - Returns the number of times the mouse was clicked.
getX( ) - Returns the x coordinate of the point at which the event occurred.
GetY() - Returns the y coordinate of the point at which the event occurred.
MouseListener Interface:
MouseEvent listener must implement the MouseListener interface, which declares the following five
abstract methods :
1. void mousePressed(MouseEvent event): Invoked when the mouse button is pressed down
2. voidmouseReleased(MouseEvent event): Invoked when the mouse button is released.
3. void mouseEntered(MouseEvent event): Invoked when the mouse enters the component.
4. void mouseExited(MouseEvent event): Invoked when the mouse exits the component.
5. void mouseClicked(MouseEvent event): Invoked when the mouse button is pressed and then
released.
Example:
public class mousedemo extends Frame implements MouseListener{
mousedemo(){
addmouseListener(this);
setvisible(true);
}
public void mousePressed(MouseEvent event){
System.out.println(“mouse is pressed”);
}
Public void mouseReleased(MouseEvent event){
System.out.println(“mouse is Released”);
}
public void mouseEntered(MouseEvent event){
System.out.println(“mouse is enterd”);
}
public void mouseExited(MouseEvent event){
System.out.println(“mouse is exited”);
}
Public void mouseClicked(MouseEvent event){
System.out.println(“mouse is clicked”);
}
public void main(String args[]){
New mousedemo();
}
KEYEVENT and KEYLISTENER Interface
Que:
1. Describe KEYEVENT and KEYLISTENER interface with example.
Ans:
KeyEvent
A KeyEvent is fired when you pressed, released,and typed a key on the source object.
KeyListener
A KeyEvent listener must implement KeyListenerinterface, which declares three abstract methods:
1. public void keyTyped(KeyEvent e) :Invoked when a key has been typed (pressed and released).
2. public void keyPressed(KeyEvent e): Invoked when a key has been pressed.
3. public void keyReleased(KeyEvent e): Invoked when a key has been released.
Example:
Methods:
String getActionCommand(): obtain the command name of the invoking ActionEvent object .
void setActionCommand(): to set the command name of the invoking ActionEvent object .
ActionListener:
ActionEvent listener must implement ActionListener interface, which declares one abstract method:
1. void actionPerformed(): When any action event occurs in an AWT component, this method is invoked.
Example:
public class actiondemo extends Frame implements ActionListener
{
Button b1=new Button();
actiondemo()
{
b1.addActionListener(this);
setvisible(true);
}
public void actionPerformed(ActionEventevent){
System.out.println(“button is pressed”);
}
public void main(String args[]){
new actiondemo();
}
}
WindowEvent and WindowListener Interface
Que:
1. Write a brief note on AWT WindowEvent Class.
Ans:
windowEvent:
A event that indicates that a window has changed its status (opened, closed, activated, deactivated,
iconified, or deiconified).
windowListener:
}
Public void windowDeiconified(WindowEvent e)
{
}
Public static void main(String[] args) {
new windemo();
}
}
ItemEvent and ItemListener Interface
ItemEvent:
ItemListener:
import java.awt.*;
import java.awt.event.*;
public class ItemListenerExample implements ItemListener{
Checkbox checkBox1,checkBox2;
Label label;
ItemListenerExample(){
Frame f= new Frame("CheckBox Example");
label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
f.add(checkBox1);
f.add(checkBox2);
f.add(label);
checkBox1.addItemListener(this);
checkBox2.addItemListener(this);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if(e.getSource()==checkBox1)
label.setText("C++ Checkbox: " );
if(e.getSource()==checkBox2)
label.setText("Java Checkbox: " );
}
public static void main(String args[])
{
new ItemListenerExample();
}
}
MouseMotionListener Interface
Adapter Classes
Que:
1. State why an adapter class is useful.
Ans:
An adapter class provides an empty implementation of all methods in an event listener interface.
Adapter classes are useful when we want to receive and process only some of the events that are
handled by a particular event listener interface.
We can define a new class to act as event listener by extending one of the adapter classes and
implementing only those events in which you are interested.
The Adapter classes with their corresponding listener interfaces are given below:
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
g.fillOval(e.getX(),e.getY(),30,30);
}
Constructor Description
MenuBar() Creates a new menu bar.
Menu() To create a default menu.
Menu(String str) str specifies the name of the Menu selection
Menu(String str, Boolean flag) Str specifies the name of the Menu selection flag represents
the popup menu if set true.
MenuItem() To create a default MenuItem.
MenuItem(String str) Str is the name shown in the Menu.
MenuItem(String str, MenuShortcut key)
Key is the short cut key for that Menu Item.
Method of Menu
Method Description
setEnabled(boolean flag) To enable or disable menu item
isEnabled() To retrieve the status of the menu item.
setLabel(String str) To change the name of the menu item.
String getLabel() To retrieve the current name of the menu item.
boolean getState() Return true if the item is checked otherwise false.
void setState(Boolean flag)
To check an item, pass true and to clear an item, pass false.
remove(int index) Removes the menu located at the specified index from the
menubar.
removeAll() Removes all menu from menu bar.
Example:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
MenuDemo()
{
super("Menu Demo");
m = new Menu("File");
m.add(new MenuItem("New"));
m.add(new MenuItem("Open"));
m.add(new MenuItem("Save"));
m.add(new MenuItem("Save As"));
m.add(new MenuItem("Print"));
m.addSeparator(); //add separator
m.add(new MenuItem("Quit"));
mbar.add(m);
m = new Menu("Help");
m.add(new MenuItem("Help"));
m.addSeparator();
m.add(new MenuItem("About"));
mbar.add(m);
setMenuBar(mbar);
addWindowListener(new WindowAdapter(){
}
});
}
public static void main(String args[])
{
MenuDemo MD= new MenuDemo();
}
}
There are many differences between java AWT and swing that are given below:
Java AWT Java Swing
Java swing components are platform-
AWT components are platform-dependent.
independent.
AWT components are heavyweight. Swing components are lightweight.
AWTdoesn't support pluggable look and feel. Swing supports pluggable look and feel.
AWT components require java.awt package. Swing components require javax.swing package.
Swing provides more powerful components such as
AWT provides less components than Swing. tables, lists, scrollpanes, color chooser,tabbed pane
etc.
AWT doesn't follows MVC (Model View
Controller) where model represents data, view
represents presentation and controller acts as Swing follows MVC.
an interface between model and view.
Swing
Que:
1. Explain any one SWING component with example.
2. Explain any two Swing controls.
3. Compare Label and JLabel controls.
4. Describe any one swing component with example.
5. What is Swing? Explain the need of Swing.
6. List out Swing component classes.
7. Explain JButton AWT control in java.
8. Explain JComboBox AWT control in java.
Ans:
Swing is part of Java Foundation Classes (JFC). It is an API for providing a graphical user
interface (GUI) for Java programs.
Swing is used to create window-based applications. It is built on the top of AWT (Abstract Windowing
Toolkit) API and entirely written in java.
Java Swing provides platform-independent and lightweight components.
It has more powerful and flexible components than AWT.
In addition to familiar components such as buttons, check boxes and labels, Swing provides several
advanced components such as tabbed panel, scroll panes, trees, tables, and lists.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Hierarchy of Java Swing classes
JFrame, JPanel, JWindow is the Swing's version of Frame, Panel and Windows respectively.
JApplet
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
JButton b;
JTextField tf;
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);
add(tf);
b.addActionListener(this);
setLayout(null);
}
JLabel
JLabel is used to display a single line of read only text.
It inherits JComponent class.
Constructor of JLabel
Constructor Description
Creates label with no image and with an empty string for the
JLabel()
title.
JLabel(Icon image) Creates a label with the specified image.
JLabel(String text) Creates a label with the specified text.
JLabel(Icon image, int Creates a label with the specified image and horizontal
horizontalAlignment) alignment.
Methods of JLabel
Constructor Description
getText() Returns the string that associate with the label.
setText(String text) Set the specified text to label.
getIcon() Returns the image that displays the label.
setIcon(Icon image) Set the image to the label.
getHorizontalAlignment() Returns the alignment of the label along the X axis.
setHorizontalAlignment(int
Sets the alignment of the label along the X axis
alignment)
Example:
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
f.add(l1);
f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
JTextField
The class JTextField is a component which allows the editing of a single line of text.
It inherits JTextComponent class.
Constructor of JLabel:
Constructor Description
JTextField() Creates a default text field.
Creates a new empty text field with the specified number of
JTextField(int columns)
character.
JTextField(String text) Creates a new text field initialized with the specified text.
Creates a new text field initialized with the specified text to be
JTextField(String text, int
displayed, and wide enough to hold the specified number of
columns)
columns.
Methods of JTextField
Method Description
getText() Return the text this text field contains (as a string).
setText() Puts the given text string into the field.
getColumns() Returns the width of this text field.
getSelectedText( ) Get the currently selected text.
Example:
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
JButton
The JButton class is used to create a labeled button.
Methods of JButton
Method Description
getLabel() Get the label of the Button.
setLabel(string text) Set the label of the Button with given text.
setEnable(boolean) Enable or disable this Button. Disabled Button cannot be clicked.
Example:
import javax.swing.*;
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
JCheckBox
The JCheckBox class is used to create a checkbox.
It is used to turn an option on (true) or off (false). Clicking on a CheckBox changes its state from "on"
to "off" or from "off" to "on ".
It inherits JToggleButton class.
Example:
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
JRadioButton
The JRadioButton class is used to create a radiobutton.
It is used to choose one option from multiple options.
It should be added in Group to select one radio button only by using ButtonGroup class.
By default radio button is not selected.
Constructors of JRadioButton:
Constructor Description
JRadioButton() Creates radio button with no text.
JRadioButton(Icon image) Creates radio button with the specified image but no text
JRadioButton(String text) Creates radio button with the specified text.
JRadioButton(String text, Icon image)
Creates radio button with the specified image and text.
JRadioButton(Icon image,boolean Creates a radio button with the specified image and selection
selected) state, but no text.
JRadioButton(String text,boolean Creates a radio button with the specified text and selection
selected) state.
JRadioButton(String text, Icon Creates a radio button with the specified text, image, and
image, boolean selected) selection state.
Methods of JRadioButton is same as JCheckBox:
Method Description
getText() Returns the label of the check box.
setText(String text) Sets the check box's label by given text.
isSelected() Check whether checkbox is selected or not.
Example:
import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
JComboBox
TheJComboBox class is used to create drop-downlist. At a time only one item can be selected from
the item list.
The JComboBox offers an editable option.
It inherits JComponent class.
Constructors of JcomboBox:
Constructor Description
JComboBox() Creates a JComboBox with a default data model.
Creates a JComboBox that takes its items from an existing
JComboBox(Object[] items)
array.
Creates a JComboBox that contains the elements in the
JComboBox(Vector<?> items)
specified Vector.
Methods of JcomboBox:
Method Description
addItem(Object object) It is used to add an item to the item list.
removeItem(Object object) It is used to delete an item from the item list.
removeAllItems() It is used to remove all the items from the list.
getItemCount() Returns the number of items in the list.
getSelectedIndex() Returns the index of the selected item.
setSelectedIndex(int index) Selects the item at given index.
getSelectedItem() Returns the selected item.
Example:
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Menus
Menu hierarchy is as given below:
JMenuBar
Constructor of JMenuBar
Constructor Description
JMenuBar() Creates a new menu bar.
Methods of JMenuBar
Method Description
JMenu add(JMenu c) Appends the specified menu to the end of the menu bar.
getComponentIndex(Component c) Returns the index of the specified component.
Returns the margin between the menubar's border and its
Insets getMargin()
menus.
Sets the margin between the menubar's border and its
void setMargin(Insets m)
menus.
JMenu getMenu(int index) Returns the menu at the specified position in the menubar.
int getMenuCount() Returns the number of items in the menu bar.
Returns true if the menu bar currently has a component
boolean isSelected()
selected.
JMenuItem
Method Description
JMenu add(JMenu c) Appends the specified menu to the end of the menu bar.
getComponentIndex(Component c)
Returns the index of the specified component.
Returns the margin between the menubar's border and its
Insets getMargin()
menus.
Sets the margin between the menubar's border and its
void setMargin(Insets m)
menus.
JMenu getMenu(int index) Returns the menu at the specified position in the menu bar.
int getMenuCount() Returns the number of items in the menu bar.
Returns true if the menu bar currently has a component
boolean isSelected()
selected.
JMenu
The JMenu class represents pull-down menu component which is deployed from a menubar.
Constructor of JMenu
Constructor Description
JMenu() Creates a JMenu with no text.
JMenu(String text) Creates a JMenu with the specified text.
Creates a JMenu with the specified text and specified asatear-
JMenu(String s, boolean b)
off menu or not.
Methods of JMenu
Method Description
Component add(Component c) Appends a component to the end of this menu.
Component add(Component c, Adds the specified component to this container at the given
int index) position.
Creates a menuitem with the specified text and append sit to
JMenuItemadd(String text)
the end of this menu
void addSeparator() Appends a new separator to the end of the menu.
JMenuItem getItem(int pos) Returns the JMenuItem at the specified position.
Returns the number of items on the menu,including
int getItemCount()
separators.
Inserts a new menu item with the specified text at a given
void insert(String text, int pos)
position.
void insertSeparator(int index) Inserts a separator at the specified position.
boolean isSelected() Returns true if the menu is currently selected.
void remove(int pos) Removes the menu item at the specified index from this menu
void remove(JMenuItem item) Removes the specified menu item from this menu.
void removeAll() Removes all menu items from this menu.