Download as pdf or txt
Download as pdf or txt
You are on page 1of 88

Course-Advanced Java Programming

(22517)
Program -Computer Engineering
Semester-5
Swings (10 M )

By
Ms. Adhatrao A.S.
Lecturer
Computer Technology Department
Brahmdevdada Mane Polytechnic, Belati, Solapur
Affiliated to
Maharashtra State Board of Technical Education, Mumbai.

Prepared by Ms.Adhatrao A S
27-10-2021 1
Introduction
 Swing in java is part of Java foundation class which is lightweight and platform
independent.
 It is used for creating window based applications. It includes components like
button, scroll bar, text field etc.
 Putting together all these components makes a graphical user interface.
 In this article, we will go through the concepts involved in the process of building
applications using swing in Java.

Prepared by Ms.Adhatrao A S
27-10-2021 2
What is Swing In Java?

 Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets for
building optimized window based applications.
 It is a part of the JFC( Java Foundation Classes). It is build on top of the AWT
API and entirely written in java.
 It is platform independent unlike AWT and has lightweight components.
 It becomes easier to build applications since we already have GUI components
like button, checkbox etc.
 This is helpful because we do not have to start from the scratch.

Prepared by Ms.Adhatrao A S
27-10-2021 3
Features of Swing
 1. Platform Independent: It is platform independent, the swing components that
are used to build the program are not platform specific. It can be used at any
platform and anywhere.
 2. Lightweight: Swing components are lightweight which helps in creating the UI
lighter. Swings component allows it to plug into the operating system user
interface framework that includes the mappings for screens or device and other
user interactions like key press and mouse movements.
 3. Plugging: It has a powerful component that can be extended to provide the
support for the user interface that helps in good look and feel to the application. It
refers to the highly modular-based architecture that allows it to plug into other
customized implementations and framework for user interfaces. Its components
are imported through a package called javax.swing.
Prepared by Ms.Adhatrao A S
27-10-2021 4
 4. Manageable: It is easy to manage and configure. Its mechanism and
composition pattern allows changing the settings at run time as well. The uniform
changes can be provided to the user interface without doing any changes to
application code.
 5. MVC: They mainly follows the concept of MVC that is Model View
Controller. With the help of this, we can do the changes in one component without
impacting or touching other components. It is known as loosely coupled
architecture as well.
 6. Customizable: Swing controls can be easily customized. It can be changed and
the visual appearance of the swing component application is independent of its
internal representation.

Prepared by Ms.Adhatrao A S
27-10-2021 5
Container Class

 Any class which has other components in it is called as a container class.


 For building GUI applications at least one container class is necessary.
 Following are the three types of container classes:
1. Panel – It is used to organize components on to a window
2. Frame – A fully functioning window with icons and titles
3. Dialog – It is like a pop up window but not fully functional like the frame

Prepared by Ms.Adhatrao A S
27-10-2021 6
difference between awt and swing
AWT Swing
AWT stands for Abstract windows toolkit. Swing is also called as JFC�s (Java Foundation classes).

AWT components are called Heavyweight component. Swings are called light weight component because swing
components sits on the top of AWT components and do
the work.

AWT components require java.awt package. Swing components require javax.swing package.

AWT components are platform dependent. Swing components are made in purely java and they are
platform independent.
This feature is not supported in AWT. We can have different look and feel in Swing.

Prepared by Ms.Adhatrao A S
27-10-2021 7
These feature is not available in AWT. Swing has many advanced features like JTabel, Jtabbed
pane which is not available in AWT. Also. Swing
components are called "lightweight" because they do not
require a native OS object to implement their
functionality. JDialog and JFrame are heavyweight,
because they do have a peer. So components like JButton,
JTextArea, etc., are lightweight because they do not have
an OS peer.
With AWT, you have 21 "peers" (one for each control and With Swing, you would have only one peer, the operating
one for the dialog itself). A "peer" is a widget provided by system's window object. All of the buttons, entry fields,
the operating system, such as a button object or an entry etc. are drawn by the Swing package on the drawing
field object. surface provided by the window object. This is the reason
that Swing has more code. It has to draw the button or
other control and implement its behavior instead of
relying on the host operating system to perform those
functions.
AWT is a thin layer of code on top of the OS. Swing is much larger. Swing also has very much richer
functionality.
Using AWT, you have to implement a lot of things Swing has them built in.
yourself. Prepared by Ms.Adhatrao A S
27-10-2021 8
Java Swing Class Hierarchy

Prepared by Ms.Adhatrao A S
27-10-2021 9
 All the components in swing like JButton, JComboBox, JList, JLabel are inherited
from the JComponent class which can be added to the container classes.
 Containers are the windows like frame and dialog boxes. Basic swing components
are the building blocks of any gui application.
 Methods like setLayout override the default layout in each container. Containers
like JFrame and JDialog can only add a component to itself.

Prepared by Ms.Adhatrao A S
27-10-2021 10
SWING UI Elements

S.No. Class & Description

1 Jlabel : JLabel object is a component for placing text in a container.

2 Jbutton :This class creates a labeled button.


JColorChooser: A JColorChooser provides a pane of controls designed to allow a
3 user to manipulate and select a color.

JCheck Box :A JCheckBox is a graphical component that can be in either


4
an on (true) or off (false) state.
JRadioButton :The JRadioButton class is a graphical component that can be in
5 either an on (true) or off (false) state. in a group.
Prepared by Ms.Adhatrao A S
27-10-2021 11
Jlist :A JList component presents the user with a scrolling list of text items.
6

JComboBox :A JComboBox component presents the user with a to show up


7 menu of choices.

JTextField: A JTextField object is a text component that allows for the


8 editing of a single line of text.

JPasswordField :A JPasswordField object is a text component specialized


9 for password entry.

JTextArea: A JTextArea object is a text component that allows editing of a


10 multiple lines of text.

Prepared by Ms.Adhatrao A S
27-10-2021 12
ImageIcon :A ImageIcon control is an implementation of the Icon interface
11
that paints Icons from Images
Jscrollbar :A Scrollbar control represents a scroll bar component in order to
12 enable the user to select from range of values.
JOptionPane :JOptionPane provides set of standard dialog boxes that prompt
13 users for a value or informs them of something.
JFileChooser :A JFileChooser control represents a dialog window from which
14
the user can select a file.
JProgressBar :As the task progresses towards completion, the progress bar
15
displays the task's percentage of completion.
Jslider :A JSlider lets the user graphically select a value by sliding a knob
16
within a bounded interval.
Jspinner :A JSpinner is a single line input field that lets the user select a
17
number or an object value from an ordered sequence.
Prepared by Ms.Adhatrao A S
27-10-2021 13
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.
 Let's see the declaration for javax.swing.JButton class.
 public class JButton extends AbstractButton implements Accessible
 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.

Prepared by Ms.Adhatrao A S
27-10-2021 14
 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 It is used to add the action listener to this


addActionListener(ActionListener a) object.
Prepared by Ms.Adhatrao A S
27-10-2021 15
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);
}
}

Prepared by Ms.Adhatrao A S
27-10-2021 16
Java JLabel

 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.
 Let's see the declaration for javax.swing.JLabel class.
 public class JLabel extends JComponent implements SwingConstants, Accessible
 Commonly used Constructors:

Prepared by Ms.Adhatrao A S
27-10-2021 17
Commonly used Constructors:

Constructor Description
JLabel() Creates a JLabel instance with no image and with 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.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text,
horizontalAlignment) image, and horizontal alignment.

Prepared by Ms.Adhatrao A S
27-10-2021 18
Commonly used Methods:

Methods Description
String getText() It returns the text string that a label displays.
void setText(String text) It defines the single line of text this component
will display.
void setHorizontalAlignment(int It sets the alignment of the label's contents along
alignment) the X axis.
Icon getIcon() It returns the graphic image that the label
displays.

int getHorizontalAlignment() It returns the alignment of the label's contents


along the X axis.

Prepared by Ms.Adhatrao A S
27-10-2021 19
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);
}
}
Prepared by Ms.Adhatrao A S
27-10-2021 20
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.
 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
JTextField(String text) Creates a new TextField initialized with the
specified text.
JTextField(String text, int Creates a new TextField initialized with the
columns) specified text and columns.
JTextField(int columns) Creates a new empty TextField with the specified
number of columns.
Prepared by Ms.Adhatrao A S
27-10-2021 21
Commonly used Methods:

Methods Description
void addActionListener(ActionListener l) It is used to add the specified action listener
to 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.

void It is used to remove the specified action


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

Prepared by Ms.Adhatrao A S
27-10-2021 22
Java JTextField 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);
}
}
Prepared by Ms.Adhatrao A S
27-10-2021 23
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
 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.

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

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

JTextArea(String s, int row, int Creates a text area with the specified number of rows and
column) columns that displays specified text.
Prepared by Ms.Adhatrao A S
27-10-2021 24
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.

void insert(String s, int position) It is used to insert the specified text on the specified
position.

void append(String s) It is used to append the given text to the end of the
document.

Prepared by Ms.Adhatrao A S
27-10-2021 25
Java JTextArea Example
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to java
tpoint");
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();
}}
Prepared by Ms.Adhatrao A S
27-10-2021 26
JPasswordField

 JPasswordField is a Swing component and an input field which facilitates the user
to enter their password. You must have seen such a field while logging in to any
website like Facebook or Gmail which shows “*” or any other character when you
type your password into the text box provided. JPasswordField is the same thing.
 Declaration of Jpasswordfield:

 public class JPasswordField extends JTextField

 As you can see, this class is a subclass of JTextField, it inherits all the properties
of a text field plus its own functionalities like masking the entered characters.

Prepared by Ms.Adhatrao A S
27-10-2021 27
 Constructor Details:
 JPasswordField(): This is the simplest constructor that creates a password field
with default document, zero column width and no (null) starting text string.
 JPasswordField(Document doc, String txt, int columns): This constructor creates a
password field with a specified document, specified column width, and specified
default password.
 JPasswordField(int columns): This constructor creates a password field with
specified column width.
 JPasswordField(String text): This constructor creates a password field with the
specified default password.
 JPasswordField(String text, int columns): This constructor creates a password
field with specified column width and specified default password.

Prepared by Ms.Adhatrao A S
27-10-2021 28
 Method details:
 char[] getPassword(): This is an important and most useful method of JPasswordField
class which returns the password, as a character array, entered in this JPasswordField.
 String getText(): This method returns the password, as a string, entered in this
JPasswordField. But this method is deprecated in Java 2 platform v1.2, replaced by the
getPassword() method.
 String getText(int offs, int len): This method returns a portion of the password, as a string,
entered in this JPasswordField. But this method is deprecated in Java 2 platform v1.2,
replaced by getPassword() method.
 void copy(): This method invokes provideErrorFeedback on the current look and feel
which initiates an error beep.
 void cut(): This method invokes provideErrorFeedback on the current look and feel which
initiates an error beep.
 boolean echoCharIsSet(): This method returns true if a character is set for echoing to this
JPasswordField. Otherwise false.

Prepared by Ms.Adhatrao A S
27-10-2021 29
 char getEchoChar(): This method returns the character which is set to this
JPasswordField for echoing.
 void setEchoChar(char c): This method sets the echo character to this password
field.
 String getUIClassID(): This method returns the name of the look and feel class
that renders this component.
 protected String paramString(): This method returns a string representation of this
password field.
 void updateUI(): This method reloads the pluggable UI of this password field.
 AccessibleContext getAccessibleContext(): This method returns the
AccessibleContext associated with this JPasswordField.

Prepared by Ms.Adhatrao A S
27-10-2021 30
Java JPasswordField Example
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);
f.setLayout(null);
f.setVisible(true);
}
}

Prepared by Ms.Adhatrao A S
27-10-2021 31
Java JCheckBox

 The JCheckBox class in JAVA can be used as a toggle to switch off or on any
functionality.
 This class basically created a checkbox which provides two options which are: on
and off. Here on and off are denoted as true or false internally by the system.
 Then on “on” state is arrived by clicking on the checkbox. Clicking on it again
changes the state of checkbox from “on” to “off”.
 This class inherits its characteristics from the JToggleButton class.

Prepared by Ms.Adhatrao A S
27-10-2021 32
 The JCheckBox class can be declared as below:
 public class JCheckBox extends JToggleButton implements Accessible.

 Explanation: Here public is access modifier which states that this class can be
used by any external or internal function. “JToggleButton” is the parent class
whose characteristics/ properties are being used by JCheckBox.

Prepared by Ms.Adhatrao A S
27-10-2021 33
 Constructor of JCheckBox in Java:
 JCheckBox(): This constructor creates a blank checkbox containing no text or
icon. Checkbox created using this constructor is by default unselected.
 JChechBox(String s): This constructor will lead to the creation of an unselected
checkbox but this checkbox will contain a text which is passed in string data type
format via a constructor parameter. In this case, we have passed String “S” which
will be displayed with the checkbox.
 JCheckBox(String text, boolean selected): This constructor is used if the
requirement is to have a checkbox that is selected by default. This functionality
was enabled via a boolean value “on” which is sent via a parameter to this
constructor. The text is also displayed with the help of this constructor which is
passed via parameters as the previous constructor.

Prepared by Ms.Adhatrao A S
27-10-2021 34
 JCheckBox(Action a): This constructor creates a checkbox having properties
derived from the action. The action is supplied with all the user required
properties to checkbox constructor. The checkbox then derives its properties from
the action.
 JCheckBox(Icon i): This constructor returns a checkbox containing an Icon that is
passed to the checkbox via a parameter in the form of “Icon i”.
 JCheckBox(Icon I, boolean selected): This constructor returns a checkbox
containing an Icon along with “on” state which is passed to the checkbox via
parameters. This checkbox will be selected by default.
 JCheckBox(String text, Icon I, boolean selected): This constructor will return a
checkbox having all the three properties applied to the checkbox. These three
properties are text, icon, and state which are passed via constructor parameters.

Prepared by Ms.Adhatrao A S
27-10-2021 35
Methods of JCheckBox in Java
 protected String paramString(): This method is used to get a string representing the state
of JCheckBox. This method is generally used by debuggers while debugging. The string
returned may vary as per its implementation, it may be null as well.
 getStateChange(): This method returns true if the value of the checkbox is changed. For
example, the value of checkbox has been changed from the state “on” to “off” or vice
versa then this transition is recorded via this method. This function is used in case we
want to trigger any action based on the change in the value of the checkbox. This is
linked to an item listener of the checkbox.
 setSelected(boolean b): This method is used to set the checkbox with the state “on” or
“off” bases on the parameter value passed. The Boolean true means “on” and false means
“off”.
 getText(): This function is used to get the text of the checkbox. We capture that returned
text and can use it as per the requirement of the user.
 Similar to the previous method, this method is used to set the text to the checkbox. The
text which is passed as a parameter in this method is passed a stext in the checkbox.
Prepared by Ms.Adhatrao A S
27-10-2021 36
Java JCheckBox Example
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();
}}
Prepared by Ms.Adhatrao A S
27-10-2021 37
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.
 It should be added in ButtonGroup to select one radio button only.

 JRadioButton class declaration


 Let's see the declaration for javax.swing.JRadioButton class.
 public class JRadioButton extends JToggleButton implements Accessible

Prepared by Ms.Adhatrao A S
27-10-2021 38
 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.
JRadioButton(String s, boolean selected) Creates a radio button with the specified
text and selected status.

Prepared by Ms.Adhatrao A S
27-10-2021 39
 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

Prepared by Ms.Adhatrao A S
27-10-2021 40
Java JRadioButton 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();
}
} Prepared by Ms.Adhatrao A S
27-10-2021 41
Java JComboBox
 JComboBox belongs to the Java Swing package. It extends the JComponent class.
JComboBox is represented by a popup menu that contains the list of elements and the
user could select an option or element from that list.
 It can be editable or not depending upon the need and the programmer. By default, it is
not editable combining the features of a button and a drop-down list.
 The JComboBox which is not editable has features of the text field and a drop-down list.
Users can type or can click on the arrow button to view the drop-down list.
 Combo Boxes require less space and hence very useful when size is small or limited.
 JComboBox class declaration
Let's see the declaration for javax.swing.JComboBox class.
public class JComboBox extends JComponent implements ItemSelectable,
ListDataListener, ActionListener, Accessible

Prepared by Ms.Adhatrao A S
27-10-2021 42
Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data


model.

JComboBox(Object[] items) Creates a JComboBox that contains the


elements in the specified array.

JComboBox(Vector<?> items) Creates a JComboBox that contains the


elements in the specified Vector.

Prepared by Ms.Adhatrao A S
27-10-2021 43
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.

void setEditable(boolean b) It is used to determine whether the JComboBox is


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

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

Prepared by Ms.Adhatrao A S
27-10-2021 44
Java JComboBox 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();
}
}
Prepared by Ms.Adhatrao A S
27-10-2021 45
ADVANCED SWING COMPONENTS

Prepared by Ms.Adhatrao A S
27-10-2021 46
Java JTabbedPane

 JTabbedPane class is one of the many classes (such as JButton, JTextArea, JMenu,
JTextField, etc)that ‘javax.swing’ java package provides for java swing APIs.
 Java Swing package is part of the Java’s foundation classes, JFCs.These
foundation classes are used to create graphical user interfaces, window-based
applications using available GUI components which makes easier for a
programmer to develop desktop applications. They are written completely in java
top of AWT, Abstract Windows Toolkit.
 But opposite to AWT, Java Swing packages provide platform-independent
components. These components are comparatively light weighted too.

Prepared by Ms.Adhatrao A S
27-10-2021 47
What is JTabbedPane?
 JTabbedPane is one of the classes provided by the swing package in java. It is
very useful, as it provides the flexibility to the user to switch between different
groups of components he desires to see, by simply clicking on one of the tabs. The
tabs can be given different titles or icons.
 Here is an everyday example of such a window, that has several tabs that can be
accessed by clicking on the tabs.

Prepared by Ms.Adhatrao A S
27-10-2021 48
 A simple ‘properties’ window of a local disk (here, Local Disk F: Properties
window on my system) on your computer system has multiple tabs, named
General, Tools, Hardware, etc that you are able to access, by clicking on one of
them, is a perfect example of the tabbed panes.
 In other words, the JTabbedPane helps you to have several components share the
same place. The user easily chooses which component he wants to see by
choosing or clicking on the desired tab.

Prepared by Ms.Adhatrao A S
27-10-2021 49
JTabbedPane Tab Indexing and
Placement
 The tabs are represented by an index, which gets decided according to the place at
or the position in which the tab was added.
 To understand this, let’s suppose you added your first tab. Then its index will be
equal to ‘0’ and your next tab will have an index equal to ‘1’ and going by the
fashion, your last added tab’s index will be equal to ‘tab count minus 1’.
 The Tabbed Pane classes use a single selection model that represents ‘a set of tab
indexes’ as well as the ‘currently selected index’ i.e. the selected tab’s index.
 By default, the tabs are placed at the TOP location, as you can see in the above
window’s property tabbed pane. You can change this tab placement to any of the
directions like LEFT, RIGHT or Bottom by the use of a method called,
setTabPlacement method.

Prepared by Ms.Adhatrao A S
27-10-2021 50
 Commonly used Constructors:

Constructor Description

JTabbedPane() Creates an empty TabbedPane with a default


tab 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
tabLayoutPolicy) specified tab placement and tab layout policy.

Prepared by Ms.Adhatrao A S
27-10-2021 51
Java JTabbedPane Example
import javax.swing.*; f.setSize(400,400);
public class TabbedPaneExample { f.setLayout(null);
JFrame f; f.setVisible(true);
TabbedPaneExample(){ }
f=new JFrame(); public static void main(String[] args) {
JTextArea ta=new JTextArea(200,200); new TabbedPaneExample();
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);

Prepared by Ms.Adhatrao A S
27-10-2021 52
JScrollPane in Java
 ScrollPane is used to give a scrollable view to your component. When the screen
size is small or limited, we can use a scroll pane to showcase a large component or
a component whose size changes dynamically.
 The component should be lightweight like image, table, text, textarea, etc.
JScrollPane component should be inside the container like JFrame or JPanel.
 It is an important component in Graphic programming, especially your need to
handle and display a large amount of data.
 In this topic, we are going to learn about JScrollPane in Java. When we have
limited screen size, then we need to use scroll pane for the following two
conditions:
 To display a large component.
 To display a dynamically size changeable component.
Prepared by Ms.Adhatrao A S
27-10-2021 53
 JScrollPane class is a combination of viewports and scrollbars. It will connect our
viewport with the scrollbar. We can control our scrollbars appearances by using
scrollbar display policy properties:
 verticalScrollbarPolicy and horizontalScrollbarPolicy.
 Both these properties can have values AS_NEEDED, ALWAYS, or NEVER. It
also has two additional viewports:
 rowHeading – Used to scroll horizontally
 columnHeading – Used to scroll vertically

Prepared by Ms.Adhatrao A S
27-10-2021 54
Prepared by Ms.Adhatrao A S
27-10-2021 55
Constructors

Constructor Purpose

JScrollPane() It creates a scroll pane. The Component parameter,


when present, sets the scroll pane's client. The two
JScrollPane(Component) int parameters, when present, set the vertical and
horizontal scroll bar policies (respectively).

JScrollPane(int, int)

JScrollPane(Component, int, int)

Prepared by Ms.Adhatrao A S
27-10-2021 56
Useful Methods
Modifier Method Description

void setColumnHeaderView(Co It sets the column header for the scroll pane.
mponent)

void setRowHeaderView(Comp It sets the row header for the scroll pane.
onent)

void setCorner(String, It sets or gets the specified corner. The int parameter
Component) specifies which corner and must be one of the following
constants defined in ScrollPaneConstants:
Component getCorner(String) UPPER_LEFT_CORNER, UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER, LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER, UPPER_TRAILING_CORNER.

void setViewportView(Component) Set the scroll pane's client.


Prepared by Ms.Adhatrao A S
27-10-2021 57
Prepared by Ms.Adhatrao A S
27-10-2021 58
JTree in Java
 JTree is a concept used in Java swing methodology. It is used to display
hierarchical data which is in a particular order.
 It also has a root node which is the most important node in the Java framework.
Also, the Jtree concept is used in programming languages wherever a hierarchy of
data has to be displayed.
 There are children nodes in which the display of the children nodes are also
shown.
 There are children nodes for every root node.
 However, if there is no children node for a particular root node then that node is
referred to as the leaf node.

Prepared by Ms.Adhatrao A S
27-10-2021 59
 An example of a Jtree implementation is shown below where there are vegetables
and fruits as the root node because they get subdivided into many other nodes. The
children nodes under this case are capsicum, carrot, cabbage, and potato which
comes under the root node Vegetables. Also, other children nodes are banana,
mango, apple and grapes which come under the root node Fruits which can also be
created.

Prepared by Ms.Adhatrao A S
27-10-2021 60
Working of JTree in Java

 There can be multiple nodes under a root node also known as the children node.
There are also instances of JTable, JFile, and JList.
 JTable is used to display a table of any size while JList gives a dropdown list from
which we can select an item and use it in our display.
 There is also usage of JFrame in the JTree list which can be used to clarify and
build a frame in the Java programming language.

Prepared by Ms.Adhatrao A S
27-10-2021 61
Constructors

 Jtree()– A constructor has the same name as the class name and it does not have
any return value. It creates a simple model for class JTree.
 JTree(Object value[])– In this case, an object is passéd through the constructor.
All the objects passed are the child of the root node which is represented at a
lower level than the root node.
 Jtree(TreeNode root)– Here the root node is TreeNode which is built according
to the commands given. All the child notes will fall under the root node TreeNode.

Prepared by Ms.Adhatrao A S
27-10-2021 62
Methods

 Some of the methods are as follows:


 Public TreeModel getModel()– It displays the model of the tree whose data is
displayed using the Jtree in Java programming language.
 Public int getRowCount()– The mentioned function is used to count the number
of rows in the Jtree example. The number of rows also mentions the number of
child nodes that are present under the root node of the Jtree.
 Public void addTreeSelectionListener(TreeSelectionListener)– Adds a listener
in the tree selection in the Jtree panel.

Prepared by Ms.Adhatrao A S
27-10-2021 63
Example of JTree in Java
 First, we see a Jtree example in the coding language.
 The Jtree is a part of Swing methodology and it is derived from that.
 First of all the javax.swing file is imported and then the Class Example is created.
 There is a single root node in the program and there are multiple child nodes in the
program. There can be different nodes that can be created under a single root
node.
 In the following program, we show a single root node that is color and then we
notice that there is a child node called state.
 Now under state node, there are various states which are under the node which are
known as child nodes. The child nodes are added in the code very easily. There
can be other states that can be added as well.

Prepared by Ms.Adhatrao A S
27-10-2021 64
 Basically a Jtree is used to create a hierarchy in the programming concept.
 The first one comes at the top while the last one comes at the bottom.
 There can be sub-nodes to a root node that is created.
 This example is a program where hierarchy is a priority and then comes the
variables that are present.
 Obviously, Java being an object-oriented programming language there is a Default
Mutable Tree Node that is given and then the nodes are created.

Prepared by Ms.Adhatrao A S
27-10-2021 65
 A root node without child nodes is known as a leaf node.
 We can also set the size of the node created.
 In this program, we set the size as 150 and 150 that is the height and width of the
node that is being created.
 There is also a main() that is created which helps in the main formation of the
program.
 There is no IO exception in this case so the import java.io.* the package is not
exported. The String argument is also created in the main() which is the default.

Prepared by Ms.Adhatrao A S
27-10-2021 66
 import javax.swing.*; DefaultMutableTreeNode wb=new
import javax.swing.tree.DefaultMutableTreeNode; DefaultMutableTreeNode("West Bengal");
public class Example { DefaultMutableTreeNode del=new
JFrame f; DefaultMutableTreeNode("Delhi");
Example(){ DefaultMutableTreeNode ap=new
f=new JFrame(); DefaultMutableTreeNode("Andhra Pradesh");
DefaultMutableTreeNode country=new DefaultMutableTreeNode tn=new
DefaultMutableTreeNode("Tamil Nadu");
DefaultMutableTreeNode("India");
state.add(wb); state.add(del); state.add(ap); state.add(tn);
DefaultMutableTreeNode state=new JTree jt=new JTree(state);
DefaultMutableTreeNode("States"); f.add(jt);
country.add(state); f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new Example();
}}

Prepared by Ms.Adhatrao A S
27-10-2021 67
Prepared by Ms.Adhatrao A S
27-10-2021 68
JTable in Java

 In Java, JTable is used to edit or display 2-D data which consists of rows and
columns.
 It is almost similar to a spreadsheet that contains data in a tabular form. JTable
can be created by instantiating the class javax.swing.JTable. Let us look into
syntax, constructor, and methods of JTable in Java in detail.
 Syntax of JTable in Java:

 JTable jt=new JTable();

Prepared by Ms.Adhatrao A S
27-10-2021 69
 Constructors of JTable in Java
 JTable in Java has three constructors. They are:
 JTable(): A new table will be created with empty cells.
 JTable(int r, int c): A table will be created with the size as r*c.
 JTable(Object[ ][ ] d, Object [ ]col): A table will be created with the specified
data where []col describes the names of column.

Prepared by Ms.Adhatrao A S
27-10-2021 70
Methods of JTable in Java
 addColumn(TableColumn c): A column c will be added to the column array end of the
JTable column model.
 clearSelection(): The columns and rows which are selected will be deselected.
 columnAdded(TableColumnModelEvente v): When a column is added to the column
model of the table, this method will be called.
 columnMoved(TableColumnModelEvente v): When a column repositions, this method
will be called.
 columnMarginChanged(ChangeEvente v): When a column repositions due to margin
change, this method will be called.
 columnRemoved(TableColumnModelEvent e): This method will be called when a
column is removed from the column model of the table.
 columnSelectionChanged(ListSelectionEvente v): When the selection model is changed,
this method will be called.
 convertColumnIndexToModel(int viewColumnInde x): Column in the view at
viewColumnIndex will be mapped to the column index in the table model.
Prepared by Ms.Adhatrao A S
27-10-2021 71
 convertColumnIndexToView(int modelColumnIndex): The column index in the
table model at modelColumnIndex will be mapped to the view.
 getSelectedColumn(): The index of the selected column which is selected first will
be returned. It no column is selected, -1 will be returned.
 getSelectedColumnCount(): A count of selected columns will be returned.
 getSelectedColumns(): The index of the selected columns will be returned.
 getSelectedRow(): The index of the selected row which is selected first will be
returned. It no row is selected, -1 will be returned.
 getSelectedRowCount(): Count of selected rows will be returned.
 getSelectedRows(): The index of selected rows will be returned.
 removeColumnSelectionInterval(int i0, int i1 ): Columns from index 0 to 1 will be
deselected.

Prepared by Ms.Adhatrao A S
27-10-2021 72
 isCellEditable(int r, int c): If the cell in the specified row and column is editable,
true will be returned.
 removeColumn(TableColumnc): Column c will be removed from the table’s
column array.
 isCellSelected(int R, int C): If the mentioned index is in the valid range of
columns and rows and also, that position is selected, true will be returned.
 isEditing(): If the cell is editing, true will be returned.
 isRowSelected(int r): If the mentioned index is in the valid range of rows and also,
that row is selected, true will be returned.
 isColumnSelected(int c): If the mentioned index is in the valid range of columns
and also, that row is selected, true will be returned.
 moveColumn(int c, int tc): Column c gets moved to the position where column tc
is occupied.

Prepared by Ms.Adhatrao A S
27-10-2021 73
Program to display a simple JTable
// Data that will be displayed in JTable
String[][] d = {
//Java program to demonstrate JTable
{ "Sam", "29" ," Twinkle House" },
//import the following swing packages
{ "Anna Sam", " 27 ", "Happy Villa" },
import javax.swing.JFrame;
{ "Iza Norah", " 4 ", "Happy house" },
import javax.swing.JScrollPane;
};// Names of the column
import javax.swing.JTable;
String[] cn = { "Name", "Age", "House Address" };
//sample class
// JTable initialization
public class JavaTableExample {
jt = new JTable(d, cn);
// declare frame
jt.setBounds(30, 40, 200, 300);
JFrame fr;
// add it to the JScrollPane
// declare Table
JScrollPane jsp = new JScrollPane(jt);
JTable jt;
fr.add(jsp);
// Constructor of the class
fr.setSize(500, 200);
JavaTableExample()
fr.setVisible(true);
{
}
// initiallization of the frame
public static void main(String[] args)
fr = new JFrame();
{
// set Title for the frame
new JavaTableExample();
fr.setTitle("JTable Sample");
}
}
Prepared by Ms.Adhatrao A S
27-10-2021 74
Prepared by Ms.Adhatrao A S
27-10-2021 75
JProgressBar
 JProgressBar is considered to be a part of the Java Swing which is a package. It
displays visually progress of some of the mentioned task.
 In addition, it demonstrates the percentage of the mentioned task completion. The
bar in JProgressBar gets filled in as and when the mentioned task gets to its
completion stage.
 JProgressBar also displays some text in addition to displaying the percentage of
completion.

Prepared by Ms.Adhatrao A S
27-10-2021 76
Swing API

 Progress Monitoring API of the Swing includes a total of three classes that
facilitate the use of the progress bars.
 The subclass of JProgressBar, JComponent is actually considered to be the
graphical component that demonstrates the progress of the operation.
 Additionally, it also can get embedded within the other graphical components.
 Syntax:

 public class JProgressBar extends JComponent implements SwingConstants,


Accessible

Prepared by Ms.Adhatrao A S
27-10-2021 77
Constructors of JProgressBar
 JProgressBar(): This constructor is used to create the progress bar without any text on it.
 JProgressBar(int orientation): This constructor is used to create the progress bar along
with the mentioned orientation in its parameter. In case VERTICAL is mentioned as a
parameter then the vertical progress bar gets created and in case
SwingConstants.Horizontal is mentioned as a parameter then the horizontal progress bar
gets created.
 JProgressBar(int min, int max): This constructor is used to create the progress bar
along with the mentioned minimum as well as the maximum value.
 JProgressBar(int orientation, int min, int max): This constructor is used to create the
progress bar along with the mentioned minimum as well as the maximum value and also
the specified orientation in the parameter. If SwingConstants.VERTICAL is mentioned as
a parameter then the vertical progress bar gets created and in case SwingConstants.
HORIZONTAL is mentioned as a parameter then the horizontal progress bar gets created.

Prepared by Ms.Adhatrao A S
27-10-2021 78
Methods of JProgressBar
 int getMaximum(): This method is used to return the maximum value of the progress
bar.
 int getMinimum(): This method is used to return the minimum value of the progress bar.
 String getString(): This method is used to return the string representation of the current
value of the progress bar.
 void setMaximum(int t): This method is used to set the maximum value of the progress
bar to the value of t.
 void setMinimum(int t): This method is used to set the minimum value of the progress
bar to the value of t.
 void setValue(int t): This method is used to set the current value of the progress bar to
the value of t.
 void setString(String t): This method is used to set the value of the progress String to
that of t which is a String.

Prepared by Ms.Adhatrao A S
27-10-2021 79
Examples of JProgress
import javax.swing.*; public void iterate(){
public class ProgressBarExample extends JFrame{ while(i<=2000){
JProgressBar jb; jb.setValue(i);
int i=0,num=0; i=i+20;
ProgressBarExample(){ try{Thread.sleep(150);}catch(Exception e){}
jb=new JProgressBar(0,2000); }
jb.setBounds(40,40,160,30); }
jb.setValue(0); public static void main(String[] args) {
jb.setStringPainted(true); ProgressBarExample m=new ProgressBarExample(
add(jb); );
setSize(250,150); m.setVisible(true);
setLayout(null); m.iterate();
} }
}

Prepared by Ms.Adhatrao A S
27-10-2021 80
Prepared by Ms.Adhatrao A S
27-10-2021 81
ToolTip in Java Swing

 You can 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");

Prepared by Ms.Adhatrao A S
27-10-2021 82
Simple 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);
}
}
Prepared by Ms.Adhatrao A S
27-10-2021 83
MVC Architecture

 MVC is not a framework or programming language.


 It is a design pattern which helps you to write code in such a manner that it
becomes easy for distribution of task, testing and maintaining the application. It
focuses on segregating the code based on the concern of the code.
 The code is divided mostly into the three parts namely Model, View and
Controller.
 This is what MVC stands for Model-View-Controller pattern. There are also other
types of design patterns like MVC which are Model- View-ViewModel(MVVM),
Model-View-Presenter(MVP), and Model-View-Whatever(MVW).

Prepared by Ms.Adhatrao A S
27-10-2021 84
 Model View Controller design pattern mostly
focuses on separating the business logic, user
display interface and data from each other. The
purpose of three separate concerns is as
mentioned below.
 1. Model
It holds the data and the business logic or service
layer logic of the code. It contains all the data
structures, properties, and attributes of the content
that we need to transfer and manipulate. It
contains entities, domain models and view
models.

Prepared by Ms.Adhatrao A S
27-10-2021 85
 2. View
 It is the user interface that contains the layout
and displays the logic of code. It makes user
interaction with the system and helps in
accepting the inputs and displaying appropriate
outputs to the user. This code is generally
written using HTML, CSS, and javascript in
web-based applications. The View Sends the
request to the controller and renders the
response received from the controller and
displays the model content.

Prepared by Ms.Adhatrao A S
27-10-2021 86
 3. Controller
 It routes the request and response, renders the
request and communicates between the view
and model parts of the code. Controller Renders
and sends the response to the View and
manipulates the Model. Sometimes, it
manipulates and then sends the updated Model
to the View.

Prepared by Ms.Adhatrao A S
27-10-2021 87
THANK YOU

Prepared by Ms.Adhatrao A S
27-10-2021 88

You might also like