AJP Unit3
AJP Unit3
Buttons, JChoices, Lists, JText Fields and JText areas – JScrollbars – Canvases –
Containers and Layout Managers– Adding tool tips and icons – Popup menus –
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:
Advantage of JFC
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.
The methods of Component class are widely used in java swing that are given below.
Method Description
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.*;
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.
Constructor Description
Methods Description
Icon getIcon()
It is used to get the Icon of the button.
import javax.swing.*;
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.
Constructor Description
Methods Description
Icon getIcon()
It returns the graphic image that the label displays.
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.
Constructor Description
Methods Description
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.
Constructor Description
Methods Description
void setEnabled(boolean b)
It is used to enable or disable the button.
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.
Constructor Description
Methods Description
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.
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.
Constructor Description
Methods Description
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
Constructor Description
JTextField(String text, int columns) Creates a new TextField initialized with the
specified text and columns.
Methods Description
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
Constructor Description
Methods Description
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
Constructor Description
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.
Class methods
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
// creating a frame
Frame f = new Frame("Canvas Example");
// adding canvas to frame
f.add(new MyCanvas());
// main method
public static void main(String args[])
{
new CanvasExample();
}
}
// adding specifications
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
Output:
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.
• 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:
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
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 provides support for the backward binary compatibility with the previous model
The below is a Java program to handle events implementing the event deligation model:
TestApp.java:
import java.awt.*;
import java.awt.event.*;
// For searching
System.out.println("Searching...");
System.out.println("Sorting....");
int id;
TestApp app;
this.id = id;
this.app = app;
switch(id) {
case SEARCH:
app.search();
break;
case SORT:
app.sort();
break;
class GUI {
f.setLayout(new FlowLayout());
Button b;
b.addActionListener(searchCmd);
b.addActionListener(sortCmd);
List l;
l.add("Alphabetical");
l.add("Chronological");
l.addActionListener(sortCmd);
f.pack();
f.show();
Output
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.
MouseListener & The events that occur due to the user interaction
MouseEvent
MouseMotionListener with the mouse (Pointing Device).
Example
import java.awt.*;
import java.awt.event.*;
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
b.setBounds(100,120,80,30);
//register listener
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
tf.setText("Welcome");
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:
• 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
Example
import java.awt.*;
import javax.swing.*;
JTextField field;
JButton btn;
public ContainerTest() {
setTitle("Container Test");
panel.add(field);
panel.add(btn);
add(panel, BorderLayout.CENTER);
setSize(350, 275);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
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
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:
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
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.
Constructor Description
Example
import javax.swing.*;
JFrame f;
TabbedPaneExample(){
f=new JFrame();
p1.add(ta);
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);
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.
Constructor Description
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.
Example
import javax.swing.*;
public SliderExample1() {
panel.add(slider);
add(panel);
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.
Constructor Description
Method Description
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.
Example
import javax.swing.*;
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);
while(i<=2000){
jb.setValue(i);
i=i+20;
try{Thread.sleep(150);}catch(Exception e){}
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
Constructor Description
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
Example
import javax.swing.*;
JFrame f;
TableExample(){
f=new JFrame();
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
new TableExample();
Output: