0% found this document useful (0 votes)
14 views

AJP Unit3

Uploaded by

SANGEETHA San
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

AJP Unit3

Uploaded by

SANGEETHA San
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Advanced Java Programming Unit-III

Java Foundation classes(JFC) /Swings –JButtons, JLabels, JCheck boxes, JRadio

Buttons, JChoices, Lists, JText Fields and JText areas – JScrollbars – Canvases –

Event Delegation model – Exceptions – Event classes – Listener Interfaces –

Containers and Layout Managers– Adding tool tips and icons – Popup menus –

Tabbed panes – sliders –progress bars – Tables.

JFC

JFC stands for Java Foundation Classes. It is a rich and comprehensive set of GUI components
and services that simplify the development and deployment of desktop, client-side, and internet
applications. It is a superset that contains AWT. JFC extends AWT by adding many components
and services that are as follows:

API/ Feature Description

It includes everything from buttons to split panes to


tables. Many components are capable of sorting,
Swing GUI Components
printing, and drag and drop, to name a few of the
supported features.

The look and feel of Swing applications is pluggable,


allowing a choice of look and feel. For example, the
same program can use either the Java or the
Windows look and feel. Additionally, the Java
Pluggable Look-and-Feel Support
platform supports the GTK + look and feel, which
makes hundreds of existing looks and feels available
to Swing programs. Many more look-and-feel
packages are available from various sources.
It is a part of JFC that works with alternate input and
output devices. It enables assistive technologies,
Accessibility API
such as screen readers, screen magnifiers, and Braille
terminals, to get information from the UI.

It enables developers to easily incorporate high-


quality 2D graphics, text, and images in applications
Java 2D API and applets. Java 2D includes extensive APIs for
generating and sending high-quality output to
printing devices.

It allows developers to build applications that can


interact with users worldwide in their own languages
and cultural conventions. With the input method
Internationalization framework, developers can build applications that
accept text in languages that use thousands of
different characters, such as Japanese, Chinese, or
Korean.

Drag and Drop is one of the more common


metaphors used in GUI. The user is allowed to click
and "hold" a GUI object, moving it to another
window or frame in the desktop with predictable
Drag and Drop (DnD) results. It allows users to implement droppable
elements that transfer information between Java
applications and native applications. Although DnD
is not part of Swing, it is crucial to a commercial-
quality application.
In the above figure, we see that Swing sits atop of part, but not all, of the AWT components.
Swing sits on a number of the APIs that implement the various parts of AWT, including Java2D,
Drag-and-Drop, and the Accessibility API.

Advantage of JFC

• Its components are pluggable and require few lines of code.


• It retains Java qualities.
• An application that runs flawlessly on one OS runs flawlessly on another OS.
• It offers an open architecture.

Java Swing Java Swing is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.


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

The hierarchy of java swing API is given below.


Commonly used Methods of Component class

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.

sets the visibility of the component. It is by default


public void setVisible(boolean b)
false.

Java Swing Examples

There are two ways to create a frame:

• By creating the object of Frame class (association)


• By extending Frame class (inheritance)

Simple Java Swing Example

Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.
File: FirstSwingExample.java

import javax.swing.*;

public class FirstSwingExample {

public static void main(String[] args) {

JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton

b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height

f.setLayout(null);//using no layout managers

f.setVisible(true);//making the frame visible

Output
JButtons

The JButton class is used to generate a push-button control that can trigger an ActionEvent when
pressed. The ActionListener interface should be implemented in order to handle a button click
event. JButton is a container-addable component that extends the JComponent class.

JButton class declaration

public class JButton extends AbstractButton implements Accessible

Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:

Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.


void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon()
It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JButton Example

import javax.swing.*;

public class ButtonExample {

public static void main(String[] args) {

JFrame f=new JFrame("Button Example");

JButton b=new JButton("Click Here");

b.setBounds(50,100,95,30);

f.add(b);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

}
Output:

JLabels

A JLabel object can display either text, an image, or both. You can specify where in the label's
display area the label's contents are aligned by setting the vertical and horizontal alignment. By
default, labels are vertically centered in their display area.

JLabel class declaration

Let's see the declaration for javax.swing.JLabel class.

public class JLabel extends JComponent implements SwingConstants, Accessible

Commonly used Constructors:

Constructor Description

Creates a JLabel instance with no image and with


JLabel()
an empty string for the title.
JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

Creates a JLabel instance with the specified text,


JLabel(String s, Icon i, int horizontalAlignment)
image, and horizontal alignment.

Commonly used Methods:

Methods Description

String getText() t returns the text string that a label displays.

It defines the single line of text this component


void setText(String text)
will display.

It sets the alignment of the label's contents along


void setHorizontalAlignment(int alignment)
the X axis.

Icon getIcon()
It returns the graphic image that the label displays.

It returns the alignment of the label's contents


int getHorizontalAlignment()
along the X axis.

Java JLabel Example

import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}

Output:
JCheck boxes

A check box, also known by other names such as a tick box or a selection box, is an input field
provided to the user on a form which allows them to select one or more options from a
predefined list.

JCheckBox class declaration

Let's see the declaration for javax.swing.JCheckBox class.

public class JCheckBox extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

Creates an initially unselected check box button


JJCheckBox()
with no text, no icon.

Creates an initially unselected check box with


JChechBox(String s)
text.

Creates a check box with text and specifies


JCheckBox(String text, boolean selected)
whether or not it is initially selected.

Creates a check box where properties are taken


JCheckBox(Action a)
from the Action supplied.
Commonly used Methods:

Methods Description

It is used to get the AccessibleContext associated


AccessibleContext getAccessibleContext()
with this JCheckBox.

It returns a string representation of this


protected String paramString()
JCheckBox.

Java JCheckBox Exampleimport javax.swing.*;

public class CheckBoxExample


{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}

Output:

JRadio Buttons

Radio buttons, also called option buttons it is used to choose one option from multiple options. It
is widely used in exam systems or quiz. Radio buttons are always used in groups, and each
option is represented by one radio button in the group.

JRadioButton class declaration

Let's see the declaration for javax.swing.JRadioButton class.

public class JRadioButton extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified


text.
Creates a radio button with the specified text and
JRadioButton(String s, boolean selected)
selected status.

Commonly used Methods:

Methods Description

void setText(String s) It is used to set specified text on button.

String getText() It is used to return the text of the button.

void setEnabled(boolean b)
It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Example

import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}

Output:

JChoices

JComboBox is a Swing component that combines a text field and a drop-down list (Figure 12.9.
1). It lets the user either type in a selection or choose a selection from a list that appears when the
user requests it—a JComboBox 's drop-down behavior is somewhat similar to a java. awt.

JComboBox class declaration


Let's see the declaration for javax.swing.JComboBox class.

public class JComboBox extends JComponent implements ItemSelectable, ListDataListene


r, ActionListener, Accessible

Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

Creates a JComboBox that contains the elements


JComboBox(Object[] items)
in the specified array.

Creates a JComboBox that contains the elements


JComboBox(Vector<?> items)
in the specified Vector.

Commonly used Methods:

Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from the list.
It is used to determine whether the JComboBox is
void setEditable(boolean b)
editable.

void addActionListener(ActionListener a) It is used to add the ActionListener.

void addItemListener(ItemListener i) It is used to add the ItemListener.

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();
}
}
Output:

JLists

The object of JList class represents a list of text items. The list of text items can be set up so that
the user can choose either one item or multiple items. It inherits JComponent class.

JList class declaration

Let's see the declaration for javax.swing.JList class.

public class JList extends JComponent implements Scrollable, Accessible

Commonly used Constructors:

Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the


specified array.
Creates a JList that displays elements from the
JList(ListModel<ary> dataModel)
specified, non-null, model.

Commonly used Methods:

Methods Description

It is used to add a listener to the list, to be


Void addListSelectionListener(ListSelectionListener
notified each time a change to the selection
listener)
occurs.

int getSelectedIndex() It is used to return the smallest selected cell


index.

It is used to return the data model that holds a


ListModel getModel()
list of items displayed by the JList component.

It is used to create a read-only ListModel from


void setListData(Object[] listData)
an array of objects.

Example

import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}

Output:

JText Fields

The object of a JTextField class is a text component that allows the editing of a single line text. It
inherits JTextComponent class.
JTextField class declaration

Let's see the declaration for javax.swing.JTextField class.

public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

Creates a new TextField initialized with the


JTextField(String text)
specified text.

JTextField(String text, int columns) Creates a new TextField initialized with the
specified text and columns.

Creates a new empty TextField with the specified


JTextField(int columns)
number of columns.

Commonly used Methods:

Methods Description

It is used to add the specified action listener to


void addActionListener(ActionListener l)
receive action events from this textfield.
Action getAction() It returns the currently set Action for this
ActionEvent source, or null if no Action is set.

void setFont(Font f) It is used to set the current font.

It is used to remove the specified action listener so


void removeActionListener(ActionListener l) that it no longer receives action events from this
textfield.

Example

import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

Java JTextArea

The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class

JTextArea class declaration

Let's see the declaration for javax.swing.JTextArea class.

public class JTextArea extends JTextComponent

Commonly used Constructors:

Constructor Description

JTextArea() Creates a text area that displays no text initially.

Creates a text area that displays specified text


JTextArea(String s)
initially.
Creates a text area with the specified number of
JTextArea(int row, int column)
rows and columns that displays no text initially.

Creates a text area with the specified number of


JTextArea(String s, int row, int column)
rows and columns that displays specified text.

Commonly used Methods:

Methods Description

void setRows(int rows) It is used to set specified number of rows.

void setColumns(int cols) It is used to set specified number of columns.

void setFont(Font f) It is used to set the specified font.

It is used to insert the specified text on the


void insert(String s, int position)
specified position.

It is used to append the given text to the end of the


void append(String s)
document.

Example

import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}

Output:

JScrollbars

The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an
implementation of a scrollbar. It inherits JComponent class.
JScrollBar class declaration

Let's see the declaration for javax.swing.JScrollBar class.

public class JScrollBar extends JComponent implements Adjustable, Accessible

Commonly used Constructors:

Constructor Description

JScrollBar() Creates a vertical scrollbar with the initial values.

Creates a scrollbar with the specified orientation


JScrollBar(int orientation)
and the initial values.

JScrollBar(int orientation, int value, int extent, int Creates a scrollbar with the specified orientation,
min, int max) value, extent, minimum, and maximum.

Example

import javax.swing.*;
class ScrollBarExample
{
ScrollBarExample(){
JFrame f= new JFrame("Scrollbar Example");
JScrollBar s=new JScrollBar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ScrollBarExample();
}

Output:

Canvases

In java canvas is area used to draw something by java graphics. For ex. drawing an image or
rectangle. The Canvas class controls and represents a blank rectangular area where the application
can draw or trap input events from the user. It inherits the Component class.

AWT Canvas class Declaration

public class Canvas extends Component implements Accessible


Canvas Class Constructors

Sr. no. Constructor Description

1. Canvas() It constructs a new Canvas.

It constructs a new Canvas


Canvas(GraphicConfiguration
2. with the given Graphic
config)
Configuration object.

Class methods

Sr. no. Method name Description

1. void addNotify() It creates the canvas's peer.

It creates a new multi buffering


void createBufferStrategy (int
2. strategies on the particular
numBuffers)
component.

It creates a new multi buffering


void createBufferStrategy (int
strategies on the particular
3. numBuffers, BufferCapabilities
component with the given buffer
caps)
capabilities.

AccessibleContext It gets the accessible context


4.
getAccessibleContext() related to the Canvas.
It returns the buffer strategy
BufferStrategy
5. used by the particular
getBufferStrategy()
component.

It paints the canvas with given


6. void paint(Graphics g)
Graphics object.

It updates the canvas with given


7. void pdate(Graphics g)
Graphics object.

Method Inherited by Canvas Class

The Canvas has inherited above methods from the following classes:

o lang.Component
o lang.Object

Example

In the following example, we are creating a Canvas in the Frame and painting a red colored oval
inside it.

CanvasExample.java

// importing awt class


import java.awt.*;

// class to construct a frame and containing main method


public class CanvasExample
{
// class constructor
public CanvasExample()
{

// creating a frame
Frame f = new Frame("Canvas Example");
// adding canvas to frame
f.add(new MyCanvas());

// setting layout, size and visibility of frame


f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
}

// main method
public static void main(String args[])
{
new CanvasExample();
}
}

// class which inherits the Canvas class


// to create Canvas
class MyCanvas extends Canvas
{
// class constructor
public MyCanvas() {
setBackground (Color.GRAY);
setSize(300, 200);
}
// paint() method to draw inside the canvas
public void paint(Graphics g)
{

// adding specifications
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}

Output:

Event Delegation model

The delegation event model defines standard and consistent mechanisms to generate and process
events. Its concept is quite simple: 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.

The Delegation Event model is defined to handle events in GUI programming languages. The
GUI stands for Graphical User Interface, where a user graphically/visually interacts with the
system.
The GUI programming is inherently event-driven; whenever a user initiates an activity such as a
mouse activity, clicks, scrolling, etc., each is known as an event that is mapped to a code to
respond to functionality to the user. This is known as event handling.

In this section, we will discuss event processing and how to implement the delegation event
model in Java. We will also discuss the different components of an Event Model.

Basically, an Event Model is based on the following three components:

• Events
• Events Sources
• Events Listeners

Events

The Events are the objects that define state change in a source. An event can be generated as a
reaction of a user while interacting with GUI elements. Some of the event generation activities
are moving the mouse pointer, clicking on a button, pressing the keyboard key, selecting an item
from the list, and so on. We can also consider many other user operations as events.

Event Sources

A source is an object that causes and generates an event. It generates an event when the internal
state of the object is changed. The sources are allowed to generate several different types of
events.

A source must register a listener to receive notifications for a specific event. Each event contains
its registration method. Below is an example:

public void addTypeListener (TypeListener e1)

From the above syntax, the Type is the name of the event, and e1 is a reference to the event
listener.

Event Listeners

An event listener is an object that is invoked when an event triggers. The listeners require two
things; first, it must be registered with a source; however, it can be registered with several
resources to receive notification about the events. Second, it must implement the methods to
receive and process the received notifications.

Design Goals

The design goals of the event delegation model are as following:

It is easy to learn and implement

It supports a clean separation between application and GUI code.

It provides robust event handling program code which is less error-prone (strong compile-time
checking)

It is Flexible, can enable different types of application models for event flow and propagation.

It enables run-time discovery of both the component-generated events as well as observable


events.

It provides support for the backward binary compatibility with the previous model

Java Program to Implement the Event Deligation Model

The below is a Java program to handle events implementing the event deligation model:

TestApp.java:

import java.awt.*;

import java.awt.event.*;

public class TestApp {

public void search() {

// For searching

System.out.println("Searching...");

public void sort() {


// for sorting

System.out.println("Sorting....");

static public void main(String args[]) {

TestApp app = new TestApp();

GUI gui = new GUI(app);

class Command implements ActionListener {

static final int SEARCH = 0;

static final int SORT = 1;

int id;

TestApp app;

public Command(int id, TestApp app) {

this.id = id;

this.app = app;

public void actionPerformed(ActionEvent e) {

switch(id) {

case SEARCH:

app.search();

break;

case SORT:
app.sort();

break;

class GUI {

public GUI(TestApp app) {

Frame f = new Frame();

f.setLayout(new FlowLayout());

Command searchCmd = new Command(Command.SEARCH, app);

Command sortCmd = new Command(Command.SORT, app);

Button b;

f.add(b = new Button("Search"));

b.addActionListener(searchCmd);

f.add(b = new Button("Sort"));

b.addActionListener(sortCmd);

List l;

f.add(l = new List());

l.add("Alphabetical");

l.add("Chronological");

l.addActionListener(sortCmd);

f.pack();
f.show();

Output

Event Classes and Listener Interfaces

class that represent events are event class. At the root of the java event class hierarchy is
"Event Object" which is defined in java. util. Thus it is a super class of all events.

Listeners are used for handling the events generated from the source. Each of these
listeners represents interfaces that are responsible for handling events.

Event Classes in Java

Event Class Listener Interface Description

An event that indicates that a component-defined


ActionEvent ActionListener action occurred like a button click or selecting an
item from the menu-item list.

The adjustment event is emitted by an Adjustable


AdjustmentEvent AdjustmentListener
object like Scrollbar.
Event Class Listener Interface Description

An event that indicates that a component moved,


ComponentEvent ComponentListener
the size changed or changed its visibility.

When a component is added to a container (or)


ContainerEvent ContainerListener removed from it, then this event is generated by a
container object.

These are focus-related events, which include


FocusEvent FocusListener
focus, focusin, focusout, and blur.

An event that indicates whether an item was


ItemEvent ItemListener
selected or not.

An event that occurs due to a sequence of


KeyEvent KeyListener
keypresses on the keyboard.

MouseListener & The events that occur due to the user interaction
MouseEvent
MouseMotionListener with the mouse (Pointing Device).

An event that specifies that the mouse wheel was


MouseWheelEvent MouseWheelListener
rotated in a component.

An event that occurs when an object’s text


TextEvent TextListener
changes.
Event Class Listener Interface Description

An event which indicates whether a window has


WindowEvent WindowListener
changed its status or not.

Example

Java event handling by implementing ActionListener

import java.awt.*;

import java.awt.event.*;

class AEvent extends Frame implements ActionListener{

TextField tf;

AEvent(){

//create components

tf=new TextField();

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 visibility

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();

OUTPUT
Containers

The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, It is basically a screen where the where the components are placed at their specific
locations. Thus it contains and controls the layout of components.Dialog and Panel.

Types of containers:

There are four types of containers in Java AWT:

• Window
• Panel
• Frame
• 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

The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.

Frame

The Frame is the container that contain title bar and border and can have menu bars. It can have
other components like button, text field, scrollbar etc. Frame is most widely used container while
developing an AWT application.
Aspect Containers

Definition Hold other components and organize their layout.

Visual Representation Not visible, provide structure to UI elements.

Typically, do not generate events or have


Events and Listeners
listeners.

Responsible for layout management, no direct


Customizability
styling.

Reusability Not meant to be reused as standalone elements.

Hierarchical Structure Can contain other containers in a nested manner.

Utilize layout managers to arrange child


Layout Management
components.

User Interaction Users do not interact with containers directly.

Associated Libraries Part of AWT and Swing libraries in Java.

Example
import java.awt.*;

import javax.swing.*;

public class ContainerTest extends JFrame { // top-level container

JPanel panel; // low-level container

JTextField field;

JButton btn;

public ContainerTest() {

setTitle("Container Test");

panel = new JPanel();

field = new JTextField(20);

panel.add(field);

btn = new JButton("Submit");

panel.add(btn);

add(panel, BorderLayout.CENTER);

setSize(350, 275);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

setVisible(true);

public static void main(String args[]) {

new ContainerTest();

}
OUTPUT

Layout Managers

The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout managers.
There are the following classes that represent the layout managers:

• java.awt.BorderLayout
• java.awt.FlowLayout
• java.awt.GridLayout
• java.awt.CardLayout
• java.awt.GridBagLayout
• javax.swing.BoxLayout
• javax.swing.GroupLayout
• javax.swing.ScrollPaneLayout
• javax.swing.SpringLayout etc.
FlowLayout

FlowLayout is a simple layout manager that arranges components in a row, left to right,
wrapping to the next line as needed. It is ideal for scenarios where components need to
maintain their natural sizes and maintain a flow-like structure.

FlowLayoutExample.java

import javax.swing.*;
import java.awt.*;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
frame.setLayout(new FlowLayout());
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output

Adding tool tips and icons

To create a tool tip for any JComponent with setToolTipText() method. This method is
used to set up a tool tip for the component.
For example, to add tool tip to PasswordField, you need to add only one line of code:

field.setToolTipText("Enter your Password");

ToolTip Example

import javax.swing.*;
public class ToolTipExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
//Creating PasswordField and label
JPasswordField value = new JPasswordField();

value.setBounds(100,100,100,30);
value.setToolTipText("Enter your Password");
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
//Adding components to frame
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output

Popup menus

PopupMenu can be dynamically popped up at specific position within a component. It inherits


the Menu class.

AWT PopupMenu class declaration

public class PopupMenu extends Menu implements MenuContainer, Accessible

Example

import java.awt.*;
import java.awt.event.*;
class PopupMenuExample
{
PopupMenuExample(){
final Frame f= new Frame("PopupMenu Example");
final PopupMenu popupmenu = new PopupMenu("Edit");
MenuItem cut = new MenuItem("Cut");
cut.setActionCommand("Cut");
MenuItem copy = new MenuItem("Copy");
copy.setActionCommand("Copy");
MenuItem paste = new MenuItem("Paste");
paste.setActionCommand("Paste");
popupmenu.add(cut);
popupmenu.add(copy);
popupmenu.add(paste);
f.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
popupmenu.show(f , e.getX(), e.getY());
}
});
f.add(popupmenu);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PopupMenuExample();
}
}
Output

Tabbed panes

The JTabbedPane class is used to switch between a group of components by clicking on a tab
with a given title or icon. It inherits JComponent class.

JTabbedPane class declaration

Let's see the declaration for javax.swing.JTabbedPane class.

public class JTabbedPane extends JComponent implements Serializable, Accessible,


SwingConstants
Commonly used Constructors:

Constructor Description

Creates an empty TabbedPane with a default tab


JTabbedPane()
placement of JTabbedPane.Top.

JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified


tab placement.

JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified


tabLayoutPolicy) tab placement and tab layout policy.

Example

import javax.swing.*;

public class TabbedPaneExample {

JFrame f;

TabbedPaneExample(){

f=new JFrame();

JTextArea ta=new JTextArea(200,200);

JPanel p1=new JPanel();

p1.add(ta);

JPanel p2=new JPanel();

JPanel p3=new JPanel();

JTabbedPane tp=new JTabbedPane();

tp.setBounds(50,50,200,200);
tp.add("main",p1);

tp.add("visit",p2);

tp.add("help",p3);

f.add(tp);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

public static void main(String[] args) {

new TabbedPaneExample();

Output:
Sliders

A component that lets the user graphically select a value by sliding a knob within a bounded
interval. The knob is always positioned at the points that match integer values within the
specified interval. The slider can show both major tick marks, and minor tick marks between the
major ones.

The Java JSlider class is used to create the slider. By using JSlider, a user can select a value from
a specific range.

Commonly used Constructors of JSlider class

Constructor Description

creates a slider with the initial value of 50 and


JSlider()
range of 0 to 100.

creates a slider with the specified orientation set by


either JSlider.HORIZONTAL or
JSlider(int orientation)
JSlider.VERTICAL with the range 0 to 100 and
initial value 50.

creates a horizontal slider using the given min and


JSlider(int min, int max)
max.

creates a horizontal slider using the given min, max


JSlider(int min, int max, int value)
and value.
creates a slider using the given orientation, min,
JSlider(int orientation, int min, int max, int value)
max and value.

Commonly used Methods of JSlider class

Method Description

public void setMinorTickSpacing(int n) is used to set the minor tick spacing to the slider.

public void setMajorTickSpacing(int n) is used to set the major tick spacing to the slider.

is used to determine whether tick marks are


public void setPaintTicks(boolean b)
painted.

public void setPaintLabels(boolean b) is used to determine whether labels are painted.

public void setPaintTracks(boolean b) is used to determine whether track is painted.

Example

import javax.swing.*;

public class SliderExample1 extends JFrame{

public SliderExample1() {

JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);

JPanel panel=new JPanel();

panel.add(slider);
add(panel);

public static void main(String s[]) {

SliderExample1 frame=new SliderExample1();

frame.pack();

frame.setVisible(true);

Output:

progress bars

Progress Bar is an horizontal or vertical bar that visualize the progress of an operation. The class
that is used to render the progress bar is 'JProgressBar' that is the part of the Java Swing package.
It displays the progress of specific task by filling of the bar and/or displaying the percentage of
completion. It may even display the text as specified. As the task reaches its completion, the
progress bar fills up.

JProgressBar class declaration

Let's see the declaration for javax.swing.JProgressBar class.

public class JProgressBar extends JComponent implements SwingConstants, Accessible


Commonly used Constructors:

Constructor Description

It is used to create a horizontal progress bar but no


JProgressBar()
string text.

It is used to create a horizontal progress bar with


JProgressBar(int min, int max)
the specified minimum and maximum value.

It is used to create a progress bar with the specified


JProgressBar(int orient) orientation, it can be either Vertical or Horizontal
by using SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.

It is used to create a progress bar with the specified


JProgressBar(int orient, int min, int max)
orientation, minimum and maximum value.

Commonly used Methods:

Method Description

It is used to determine whether string should be


void setStringPainted(boolean b)
displayed.

void setString(String s)
It is used to set value to the progress string.
It is used to set the orientation, it may be either
vertical or horizontal by using
void setOrientation(int orientation)
SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.

It is used to set the current value on the progress


void setValue(int value)
bar.

Example

import javax.swing.*;

public class ProgressBarExample extends JFrame{

JProgressBar jb;

int i=0,num=0;

ProgressBarExample(){

jb=new JProgressBar(0,2000);

jb.setBounds(40,40,160,30);

jb.setValue(0);

jb.setStringPainted(true);

add(jb);

setSize(250,150);

setLayout(null);

public void iterate(){

while(i<=2000){
jb.setValue(i);

i=i+20;

try{Thread.sleep(150);}catch(Exception e){}

public static void main(String[] args) {

ProgressBarExample m=new ProgressBarExample();

m.setVisible(true);

m.iterate();

Output:

Tables

Tables present information in orderly rows and columns. This is useful for presenting financial
figures or representing data from a relational database. Like trees, tables in Swing are incredibly
powerful. If you go with the default options, however, they're also pretty easy to use.

The JTable class is used to display data in tabular form. It is composed of rows and columns.
JTable class declaration

Let's see the declaration for javax.swing.JTable class.

Commonly used Constructors:

Constructor Description

JTable() Creates a table with empty cells.

JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

Example

import javax.swing.*;

public class TableExample {

JFrame f;

TableExample(){

f=new JFrame();

String data[][]={ {"101","Amit","670000"},

{"102","Jai","780000"},

{"101","Sachin","700000"}};

String column[]={"ID","NAME","SALARY"};

JTable jt=new JTable(data,column);

jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);

f.add(sp);

f.setSize(300,400);

f.setVisible(true);

public static void main(String[] args)

new TableExample();

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy