0% found this document useful (0 votes)
17 views26 pages

Java CH 5 Swing

The document provides an overview of various Swing components in Java, including JFrame, JPanel, JLabel, JButton, JRadioButton, JCheckBox, JProgressBar, JFileChooser, JTextField, JPasswordField, JTextArea, and JScrollBar. Each component is described with its constructors and commonly used methods, along with example code snippets demonstrating their usage. This serves as a guide for creating graphical user interfaces in Java applications.

Uploaded by

sacobi4977
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)
17 views26 pages

Java CH 5 Swing

The document provides an overview of various Swing components in Java, including JFrame, JPanel, JLabel, JButton, JRadioButton, JCheckBox, JProgressBar, JFileChooser, JTextField, JPasswordField, JTextArea, and JScrollBar. Each component is described with its constructors and commonly used methods, along with example code snippets demonstrating their usage. This serves as a guide for creating graphical user interfaces in Java applications.

Uploaded by

sacobi4977
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/ 26

BCA SEM 4 CH 5

Swing components
Java JFrame
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame
class. JFrame works like the main window where components like labels, buttons,
textfields are added to create a GUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
Constructors

Constructor Description

JFrame() It constructs a new frame that is initially invisible.

JFrame(GraphicsConfiguration It creates a Frame in the specified GraphicsConfiguration of a


gc) screen device and a blank title.

JFrame(String title) It creates a new, initially invisible Frame with the specified title.

Example
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JFrameExample {
public static void main(String s[]) {
JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("JFrame By Example");

Page 1 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

JButton button = new JButton();


button.setText("Button");
panel.add(label);
panel.add(button);
frame.add(panel);
frame.setSize(200, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Java JPanel
The JPanel is a simplest container class. It provides space in which an application can
attach any other component. It inherits the JComponents class.
Commonly used Constructors:

Constructor Description

JPanel() It is used to create a new JPanel with a double buffer and a flow
layout.

JPanel(boolean It is used to create a new JPanel with FlowLayout and the


isDoubleBuffered) specified buffering strategy.

JPanel(LayoutManager It is used to create a new JPanel with the specified layout


layout) manager.

Page 2 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

import java.awt.*;
import javax.swing.*;
public class PanelExample {
PanelExample()
{
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}

Java JLabel

Page 3 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but a
user cannot edit it directly. It inherits JComponent class.
Commonly used Constructors:

Constructor Description

JLabel() Creates a JLabel instance with no image and with an empty string for the title.

JLabel(String Creates a JLabel instance with the specified text.


s)

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

Commonly used Methods:

Methods Description

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

void setText(String text) It defines the single line of text this component will
display.

void It sets the alignment of the label's contents along


setHorizontalAlignment(int the X axis.
alignment)

import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");

Page 4 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

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

Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits AbstractButton class.
Commonly used Constructors:

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.

Page 5 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

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.

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

Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option
from multiple options. It is widely used in exam systems or quiz.
Commonly used Constructors:

Constructor Description

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

JRadioButton(String Creates an unselected radio button with specified text.


s)

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

Page 6 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

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.

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

Java JCheckBox

Page 7 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

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.
Commonly used Constructors:

Constructor Description

JJCheckBox() Creates an initially unselected check box button with no text, no icon.

JChechBox(String s) Creates an initially unselected check box with text.

JCheckBox(String Creates a check box with text and specifies whether or not it is initially selected.
text, boolean
selected)

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

Page 8 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

Java JProgressBar
The JProgressBar class is used to display the progress of the task. It inherits JComponent
class.
Commonly used Constructors:

Constructor Description

JProgressBar() It is used to create a horizontal progress bar but no string text.

JProgressBar(int It is used to create a horizontal progress bar with the specified minimum and maximum value.
min, int max)

Commonly used Methods:

Method Description

void It is used to determine whether string should be displayed.


setStringPainted(boolean
b)

void setString(String s) It is used to set value to the progress string.

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

Page 9 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

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

Java JFileChooser
The object of JFileChooser class represents a dialog window from which the user can
select file. It inherits JComponent class
Commonly used Constructors:

import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class FileChooserExample extends JFrame implements ActionListener{
JMenuBar mb;
JMenu file;
JMenuItem open;
JTextArea ta;
FileChooserExample(){
open=new JMenuItem("Open File");
open.addActionListener(this);
file=new JMenu("File");

Page 10 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

file.add(open);
mb=new JMenuBar();
mb.setBounds(0,0,800,20);
mb.add(file);
ta=new JTextArea(800,800);
ta.setBounds(0,20,800,800);
add(mb);
add(ta);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==open){
JFileChooser fc=new JFileChooser();
int i=fc.showOpenDialog(this);
if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
String filepath=f.getPath();
try{
BufferedReader br=new BufferedReader(new FileReader(filepath));
String s1="",s2="";
while((s1=br.readLine())!=null){
s2+=s1+"\n";
}
ta.setText(s2);
br.close();
}catch (Exception ex) {ex.printStackTrace(); }
}
}
}
public static void main(String[] args) {
FileChooserExample om=new FileChooserExample();
om.setSize(500,500);
om.setLayout(null);
om.setVisible(true);

Page 11 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

om.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

Constructor Description

JFileChooser() Constructs a JFileChooser pointing to the user's default


directory.

JFileChooser(File Constructs a JFileChooser using the given File as the path.


currentDirectory)

JFileChooser(String Constructs a JFileChooser using the given path.


currentDirectoryPath)

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

Commonly used Constructors:

Page 12 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.

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

commonly used Methods:

Methods Description

void It is used to add the specified action listener to receive


addActionListener(ActionListener action events from this textfield.
l)

Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.

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

Page 13 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Java JPasswordField
The object of a JPasswordField class is a text component specialized for password entry.
It allows the editing of a single line of text. It inherits JTextField class.

Commonly used Constructors:

Constructor Description

JPasswordField() Constructs a new JPasswordField, with a default document, null starting text string,
and 0 column width.

JPasswordField(int Constructs a new empty JPasswordField with the specified number of columns.
columns)

import javax.swing.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value); f.add(l1);
f.setSize(300,300);

Page 14 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

f.setLayout(null);
f.setVisible(true);
}
}

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

Commonly used Constructors:

Constructor Description

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

JTextArea(String Creates a text area that displays specified text initially.


s)

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[])
{

Page 15 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

new TextAreaExample();
}}

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

Commonly used Constructors:

Constructor Description

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

JScrollBar(int Creates a scrollbar with the specified orientation and the initial
orientation) values.

JScrollBar(int Creates a scrollbar with the specified orientation, value, extent,


orientation, minimum, and maximum.
int value, int
extent, int
min, int max)

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

Page 16 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

}
public static void main(String args[])
{
new ScrollBarExample();
}}

Java JList
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.
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.

Commonly used Methods:

Methods Description

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


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

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

Page 17 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

ListModel getModel() It is used to return the data model that holds a list
of items displayed by the JList component.

Java JMenuBar, JMenu and JMenuItem


The JMenuBar class is used to display menubar on the window or frame. It may have
several menus.
The object of JMenu class is a pull down menu component which is displayed from the
menu bar. It inherits the JMenuItem class.
JMenuBar class declaration
1. public class JMenuBar extends JComponent implements MenuElement, Accessible
JMenu class declaration
1. public class JMenu extends JMenuItem implements MenuElement, Accessible
JMenuItem class declaration
1. public class JMenuItem extends AbstractButton implements Accessible, MenuElement
import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");

Page 18 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

menu.add(i1); menu.add(i2); menu.add(i3);


submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}}

Event Handling in Java


An event can be defined as changing the state of an object or behavior by
performing actions. Actions can be a button click, cursor movement, keypress
through keyboard or page scrolling, etc.
The java.awt.event package can be used to provide various event classes.
Classification of Events
 Foreground Events
 Background Events
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e.,
foreground events are generated due to interaction by the user on components
in Graphic User Interface (GUI). Interactions are nothing but clicking on a
button, scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as
background events. Examples of these events are operating system
failures/interrupts, operation completion, etc.

Page 19 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

Event Handling
It is a mechanism to control the events and to decide what should happen
after an event occur. To handle the events, Java follows the Delegation Event
model.
Delegation Event model
 It has Sources and Listeners.

 Source: Events are generated from the source. There are various sources
like buttons, checkboxes, list, menu-item, choice, scrollbar, text components,
windows, etc., to generate events.
 Listeners: Listeners are used for handling the events generated from the
source. Each of these listeners represents interfaces that are responsible for
handling events.
To perform Event Handling, we need to register the source with the listener.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.

Page 20 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

Event Classes in Java

Event Class Listener Interface Description

An event that indicates that a


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

The adjustment event is emitted by an


AdjustmentEvent AdjustmentListener Adjustable object like Scrollbar.

An event that indicates that a component


moved, the size changed or changed its
ComponentEvent ComponentListener visibility.

When a component is added to a


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

These are focus-related events, which


include focus, focusin, focusout, and
FocusEvent FocusListener blur.

An event that indicates whether an item


ItemEvent ItemListener was selected or not.

An event that occurs due to a sequence


KeyEvent KeyListener of keypresses on the keyboard.

The events that occur due to the user


MouseListener & interaction with the mouse (Pointing
MouseEvent MouseMotionListener Device).

Page 21 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

Event Class Listener Interface Description

An event that specifies that the mouse


MouseWheelEvent MouseWheelListener wheel was rotated in a component.

An event that occurs when an object’s


TextEvent TextListener text changes.

An event which indicates whether a


WindowEvent WindowListener window has changed its status or not.

Note: As Interfaces contains abstract methods which need to implemented by


the registered class to handle events.
Different interfaces consists of different methods which are specified below.

Listener Interface Methods

ActionListener  actionPerformed()

AdjustmentListener  adjustmentValueChanged()

 componentResized()
 componentShown()
 componentMoved()
ComponentListener  componentHidden()

 componentAdded()
ContainerListener  componentRemoved()

Page 22 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

Listener Interface Methods

 focusGained()
FocusListener  focusLost()

ItemListener  itemStateChanged()

 keyTyped()
 keyPressed()
KeyListener  keyReleased()

 mousePressed()
 mouseClicked()
 mouseEntered()
 mouseExited()
MouseListener  mouseReleased()

 mouseMoved()
MouseMotionListener  mouseDragged()

MouseWheelListener  mouseWheelMoved()

TextListener  textChanged()

 windowActivated()
 windowDeactivated()
WindowListener  windowOpened()

Page 23 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

Listener Interface Methods

 windowClosed()
 windowClosing()
 windowIconified()
 windowDeiconified()

Flow of Event Handling


1. User Interaction with a component is required to generate an event.
2. The object of the respective event class is created automatically after event
generation, and it holds all information of the event source.
3. The newly created object is passed to the methods of the registered listener.
4. The method executes and returns the result.

Java Adapter Classes


Java adapter classes provide the default implementation of listener interfaces. If you
inherit the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.
Pros of using Adapter classes:
o It assists the unrelated classes to work combinedly.
o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.
The adapter classes are found in java.awt.event,
java.awt.dnd and javax.swing.event packages. The Adapter classes with their
corresponding listener interfaces are given below.

java.awt.event Adapter classes

Adapter class Listener interface

Page 24 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

java.awt.dnd Adapter classes

Adapter class Listener interface

DragSourceAdapter DragSourceListener

DragTargetAdapter DragTargetListener

javax.swing.event Adapter classes

Adapter class Listener interface

MouseInputAdapter MouseInputListener

InternalFrameAdapter InternalFrameListener

Page 25 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE


BCA SEM 4 CH 5

Page 26 of 26 WELLKNOWN COLLEGE OF COMPUTER SCIENCE

You might also like