You are on page 1of 108

Prashant bhandare

Chapter 2

Swings

-by-
Prof. Bhandare P. S.
SVERI’s COE(Poly), Pandharpur
Syllabus
Prashant bhandare

Unit no Content Hrs &


& name Marks

2.1 Introduction to swing: Swing features,


Difference between AWT and Swing.

2.2 Swing Components: JApplet, Icons and


Labels, Text Fields, Combo Boxes.

Unit II - 2.3 Buttons: The JButton, Check Boxes, Radio 8 hrs


Swing Buttons. 8 marks
2.4 Advanced Swing Components: Tabbed
Panes, Scroll Panes, Trees, Tables, Progress bar,
tool tips.

2.5 MVC Architecture.


About title of chapter
Prashant bhandare

 The title of chapter “Swing” gives idea that


this chapter contains the advanced controls
added to the window or applet so that it will
look better & handle smoothly.
Central idea of chapter
Prashant bhandare

 This chapter is important because in this


chapter it included new components that
are added to frame or applet which are
lightweight & have attractive look.
Prashant bhandare

Importance of chapter
 This chapter is important because in this
chapter students are going to learn MVC
architecture which helpful for software
development.
Prashant bhandare

Objectives of chapter:
 By studying this chapter students are going
to learn
1. Differentiate between AWT and Swing on the
given aspect.
2. Develop Graphical user interface (GUI)
programs using swing components for the given
problem.
3. Use the given type of button in Java based GUI.
4. Develop Graphical user interface (GUI)
programs using advanced swing components for
the given problem.
Java Swing
Prashant bhandare

 Introduced in 1997, Swing was included as part of the


Java Foundation Classes (JFC).

 Swing was initially available for use with Java 1.1 as a


separate library. However, beginning with Java 1.2, Swing
(and the rest of the JFC) was fully integrated into Java.

 It is built on the top of AWT (Abstract Windowing


Toolkit) API and entirely written in java.

 Unlike AWT, Java Swing provides platform-independent


and lightweight components.

 The javax.swing package provides classes for java swing


API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
 The AWT defines a basic set of controls,
Prashant bhandare

windows, and dialog boxes that support a


usable, but limited graphical interface.

 One reason for the limited nature of the AWT is


that it translates its various visual components
into their corresponding, platform-specific
equivalents, or peers.

 This means that the look and feel of a


component is defined by the platform, not by
Java.

 Because the AWT components use native code


resources, they are referred to as heavyweight.
Swing Features
Prashant bhandare

1. lightweight components

2. a pluggable look and feel.


Swing Components Are Lightweight
Prashant bhandare

 Swing components are lightweight.

 This means that they are written entirely in Java


and do not map directly to platform-specific
peers.

 Thus, lightweight components are more efficient


and more flexible.

 Furthermore, because lightweight components


do not translate into native peers, the look and
feel of each component is determined by Swing,
not by the underlying operating system.
A pluggable look and feel.
Prashant bhandare

 Swing supports a pluggable look and feel


(PLAF).

 Because each Swing component is rendered


by Java code rather than by native peers, the
look and feel of a component is under the
control of Swing.

 This fact means that it is possible to separate


the look and feel of a component from the
logic of the component, and this is what
Swing does
Prashant bhandare
 Java 8 provides look-and-feels, such as metal
and Nimbus, that are available to all Swing
users.

 The metal look and feel is also called the Java


look and feel.

 It is platform-independent and available in all


Java execution environments.

 It is also the default look and feel.

 Windows environments also have access to the


Windows look and feel.
Difference between AWT and Swing
Prashant bhandare

No. Java AWT Java Swing


AWT components are platform- Java swing components are platform-
1)
dependent. independent.

2) AWT components are heavyweight. Swing components are lightweight.

AWT doesn't support pluggable


3) Swing supports pluggable look and feel.
look and feel.

Swing provides more powerful components


AWT provides less components than
4) such as tables, lists, scrollpanes,
Swing.
colorchooser, tabbedpane etc.

AWT doesn't follows MVC(Model


View Controller) where model
represents data, view represents
5) Swing follows MVC.
presentation and controller acts as
an interface between model and
view.
Hierarchy of Java Swing classes
Prashant bhandare
Simple Java Swing Example
Prashant bhandare

import javax.swing.*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();//creating instance of JFrame

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


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

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

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


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
Swing by Association inside constructor
Prashant bhandare

 import javax.swing.*;
 public class Simple {
 JFrame f;
 Simple(){
 f=new JFrame();//creating instance of JFrame

 JButton b=new JButton("click");//creating instance of JButton
 b.setBounds(130,100,100, 40);

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

 f.setSize(400,500);//400 width and 500 height
 f.setLayout(null);//using no layout managers
 f.setVisible(true);//making the frame visible
 }

 public static void main(String[] args) {
 new Simple();
 }
 }
Simple example of Swing by inheritance
Prashant bhandare

 import javax.swing.*;
 public class Simple2 extends Jframe {
 JFrame f;
 Simple2(){
 JButton b=new JButton("click");//create button
 b.setBounds(130,100,100, 40);
 add(b);//adding button on frame
 setSize(400,500);
 setLayout(null);
 setVisible(true);
 }
 public static void main(String[] args) {
 new Simple2();
 }}
JApplet
Prashant bhandare

 Swing-based applets are similar to AWT-based applets, but with


an important difference: A Swing applet extends JApplet rather
than Applet.

 JApplet is derived from Applet. Thus, JApplet includes all of the


functionality found in Applet and adds support for Swing.

 JApplet is a top-level Swing container, which means that it is not


derived from JComponent.

 Because JApplet is a top-level container, it includes the various


panes described earlier.

 This means that all components are added to JApplet’s content


pane in the same way that components are added to JFrame’s
content pane.
Swing Components
Prashant bhandare

 Jlabel class
 JButton class
 JRadioButton class
 JTextArea class
 JComboBox class
 JTable class
 JProgressBar class
 JSlider class
 OpenDialog Box
 BorderLayout
 GridLayout
 FlowLayout
 CardLayout
JLabel and ImageIcon
Prashant bhandare

 JLabel is Swing’s easiest-to-use component. It


creates a label.

 JLabel can be used to display text and/or an


icon. It is a passive component in that it does not
respond to user input.

 JLabel defines several constructors. Here are


three of them:
◦ JLabel()
◦ JLabel(Icon icon)
◦ JLabel(String str)
◦ JLabel(String str, Icon icon, int align)
 Here,
Prashant bhandare str and icon are the text and icon used
for the label.

 The align argument specifies the horizontal


alignment of the text and/or icon within the
dimensions of the label.

 It must be one of the following values:


LEFT, RIGHT, CENTER, LEADING, or
TRAILING.

 These constants are defined in the


SwingConstants interface, along with several
others used by the Swing classes.

Prashant bhandare
icons are specified by objects of type Icon,
which is an interface defined by Swing.

 The easiest way to obtain an icon is to use the


ImageIcon class. ImageIcon implements Icon
and encapsulates an image.

 Thus, an object of type ImageIcon can be


passed as an argument to the Icon parameter of
JLabel’s constructor.

 There are several ways to provide the image,


including reading it from a file or downloading
it from a URL.
 Here
Prashant bhandare
is the ImageIcon constructor used by
the example in this section:
◦ ImageIcon(String filename)

 The icon and text associated with the label


can be obtained by the following methods:
◦ Icon getIcon( )
◦ String getText( )

 The icon and text associated with a label can


be set by these methods:
◦ void setIcon(Icon icon)
◦ void setText(String str)
 import javax.swing.*;
Prashant bhandare

 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);
 }
 }
JButton
Prashant bhandare

 The JButton class provides the functionality


of a push button.

 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:
Prashant bhandare

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.

It creates a button with the specified text and icon


JButton(String
object.
str, Icon icon)
Prashant bhandare

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(ActionListen
object.
er a)
Java JButton Example
Prashant bhandare

 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);
 }
 }
Example of displaying image on the button:
Prashant bhandare

 import javax.swing.*;
 public class ButtonExample{
 ButtonExample(){
 JFrame f=new JFrame("Button Example");
 JButton b=new JButton(new ImageIcon("D:\\icon.png"));
 b.setBounds(100,100,100, 40);
 f.add(b);
 f.setSize(300,400);
 f.setLayout(null);
 f.setVisible(true);
 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 public static void main(String[] args) {
 new ButtonExample();
 }
 }
Java JTextField
Prashant bhandare

 JTextField is the simplest Swing text component.

 It is also probably its most widely used text


component.

 JTextField allows you to edit one line of text. It is


derived from JTextComponent, which provides the
basic functionality common to Swing text
components.

 JTextField uses the Document interface for its model.

 The object of a JTextField class is a text component


that allows the editing of a single line text.
Prashant bhandare
 It inherits JTextComponent class.
 JTextField’s constructors are shown here:

Constructor Description
JTextField() Creates a new TextField

Creates a new TextField initialized with


JTextField(String text)
the specified text.

JTextField(String text, int Creates a new TextField initialized with


columns) the specified text and columns.

Creates a new empty TextField with the


JTextField(int columns)
specified number of columns.
Commonly used Methods:
Prashant bhandare

Methods Description

void It is used to add the specified


addActionListener(ActionListener action listener to receive action
l) events from this textfield.

It returns the currently set Action


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

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

It is used to remove the specified


void
action listener so that it no longer
removeActionListener(ActionListe
receives action events from this
ner l)
textfield.
Java JTextField Example
Prashant bhandare

 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);
 }
 }
Java JTextArea
Prashant bhandare

 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


Prashant bhandare

Commonly used Constructors:

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

Creates a text area with the specified


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

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 It is used to insert the specified text on the


position) specified position.

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


void append(String s)
the document.
Java JTextArea Example
Prashant bhandare

 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();
 }}
Java JPasswordField
Prashant bhandare

 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.


Prashant bhandare

Commonly used Constructors:


Constructor Description

Constructs a new JPasswordField, with a


JPasswordField() default document, null starting text string,
and 0 column width.

JPasswordField(int Constructs a new empty JPasswordField


columns) with the specified number of columns.

JPasswordField(String Constructs a new JPasswordField


text) initialized with the specified text.

Construct a new JPasswordField


JPasswordField(String
initialized with the specified text and
text, int columns)
columns.
Java JPasswordField Example
Prashant bhandare

 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);
 }
 }
Java JCheckBox
Prashant bhandare

 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:
Prashant bhandare

Constructor Description

Creates an initially unselected check box


JCheckBox()
button with no text, no icon.

Creates an initially unselected check box


JChechBox(String s)
with text.

JCheckBox(String text, Creates a check box with text and specifies


boolean selected) whether or not it is initially selected.

Creates a check box where properties are


JCheckBox(Action a)
taken from the Action supplied.
Prashant bhandare

Commonly used Methods:

Methods Description

AccessibleContext It is used to get the AccessibleContext


getAccessibleContext() associated with this JCheckBox.

protected String It returns a string representation of


paramString() this JCheckBox.
Java JCheckBox Example
Prashant bhandare

 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();
 }}
Java JRadioButton
Prashant bhandare

 Radio buttons are a group of mutually exclusive


buttons, in which only one button can be selected at
any one time.

 They are supported by the JRadioButton class, which


extends JToggleButton.

 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.
Prashant bhandare

Commonly used Constructors:

Constructor Description

Creates an unselected radio button with


JRadioButton()
no text.

Creates an unselected radio button with


JRadioButton(String s)
specified text.

JRadioButton(String s, Creates a radio button with the specified


boolean selected) text and selected status.
Commonly used Methods:
Prashant bhandare

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.

It is used to set the specified Icon on the


void setIcon(Icon b)
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.
Java JRadioButton Example
Prashant bhandare

 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();
Prashant bhandare

 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 JComboBox
Prashant bhandare

 Swing provides a combo box (a


combination of a text field and a drop-down
list) through the JComboBox class.

A combo box normally displays one entry,


but it will also display a drop-down list that
allows a user to select a different entry.

 You can also create a combo box that lets


the user enter a selection into the text field
Commonly used Constructors:
Prashant bhandare

Constructor Description

Creates a JComboBox with a default data


JComboBox()
model.

JComboBox(Object[] Creates a JComboBox that contains the


items) elements in the specified array.

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


items) elements in the specified Vector.
Commonly used Methods:
Prashant bhandare

Methods Description

It is used to add an item to the


void addItem(Object anObject)
item list.

void removeItem(Object It is used to delete an item to the


anObject) item list.

It is used to remove all the items


void removeAllItems()
from the list.

It is used to determine whether


void setEditable(boolean b)
the JComboBox is editable.
void
It is used to add the
addActionListener(ActionListene
ActionListener.
r a)
void
It is used to add the ItemListener.
addItemListener(ItemListener i)
Java JComboBox Example
Prashant bhandare

 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();
 } }
Java JList
Prashant bhandare

 In Swing, the basic list class is called JList.

 It supports the selection of one or more items from a list.


Although the list often consists of strings, it is possible to
create a list of just about any object that can be displayed.

 JList is so widely used in Java that it is highly unlikely


that you have not seen one before.

 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.


Prashant bhandare

Commonly used Constructors:

Constructor Description

Creates a JList with an empty, read-only,


JList()
model.

Creates a JList that displays the elements in the


JList(ary[] listData)
specified array.

JList(ListModel<ary> Creates a JList that displays elements from the


dataModel) specified, non-null, model.
Prashant bhandare

Commonly used Methods:


Methods Description

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


addListSelectionListener(ListS to be notified each time a change to
electionListener listener) the selection occurs.

It is used to return the smallest


int getSelectedIndex()
selected cell index.

It is used to return the data model


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

void setListData(Object[] It is used to create a read-only


listData) ListModel from an array of objects.
Java JList Example
Prashant bhandare

 import javax.swing.*;
 import java.awt.*;
 class jlistdemo
 {

 public static void main(String arg[])


 {
 JFrame jf=new JFrame("List example");
 jf.setSize(500,500);
 jf.setVisible(true);
 jf.setLayout(new FlowLayout());
Prashant bhandare

 String
s[]={"AAA","BBB","CCC","DDD","EEE",
"FFF"};
 JList jl=new JList(s);
 jf.add(jl);
 }
 }
Prashant bhandare

Java JTable

 The JTable class is used to display data in


tabular form. It is composed of rows and
columns.

Commonly used Constructors:


Constructor Description
Creates a table with empty
JTable()
cells.
JTable(Object[][] rows, Creates a table with the
Object[] columns) specified data.
Java JTable Example
Prashant bhandare

 import javax.swing.*;
 public class TableExample {
 JFrame f;
 TableExample(){
 f=new JFrame();
 String data[][]={ {"101","Amit","670000"},
 {"102","Jai","780000"},
 {"101","Sachin","700000"}};
 String column[]={"ID","NAME","SALARY"};
 JTable jt=new JTable(data,column);
 jt.setBounds(30,40,200,300);
 JScrollPane sp=new JScrollPane(jt);
 f.add(sp);
 f.setSize(300,400);
 f.setVisible(true);
 }
 public static void main(String[] args) {
 new TableExample();
 }
 }
Java JOptionPane
Prashant bhandare

 The JOptionPane class is used to provide


standard dialog boxes such as message
dialog box, confirm dialog box and input
dialog box.

 These dialog boxes are used to display


information or get input from the user.

 The JOptionPane class inherits JComponent


class.
Prashant bhandare
Common Constructors of JOptionPane
class

Constructor Description

It is used to create a JOptionPane with a test


JOptionPane()
message.

It is used to create an instance of


JOptionPane(Object message)
JOptionPane to display a message.

It is used to create an instance of


JOptionPane(Object message,
JOptionPane to display a message with
int messageType
specified message type and default options.
Common Methods of JOptionPane class
Prashant bhandare

Methods Description
It is used to create and return a new parentless JDialog
JDialog createDialog(String title)
with the specified title.

static void
It is used to create an information-message dialog titled
showMessageDialog(Component
"Message".
parentComponent, Object message)

static void
showMessageDialog(Component It is used to create a message dialog with given title and
parentComponent, Object message, messageType.
String title, int messageType)

static int
It is used to create a dialog with the options Yes, No and
showConfirmDialog(Component
Cancel; with the title, Select an Option.
parentComponent, Object message)

static String
It is used to show a question-message dialog requesting
showInputDialog(Component
input from the user parented to parentComponent.
parentComponent, Object message)

void setInputValue(Object It is used to set the input value that was selected or input by
newValue) the user.
Java JOptionPane Example:
Prashant bhandare

showMessageDialog()
 import javax.swing.*;
 public class OptionPaneExample {
 JFrame f;
 OptionPaneExample(){
 f=new JFrame();
 JOptionPane.showMessageDialog(f,"Hello, Welcome to
Javatpoint.");
 }
 public static void main(String[] args) {
 new OptionPaneExample();
 }
 }
Java JOptionPane Example
Prashant bhandare

Alert message
 import javax.swing.*;
 public class OptionPaneExample {
 JFrame f;
 OptionPaneExample(){
 f=new JFrame();
 JOptionPane.showMessageDialog(f,"Successfully
Updated.","Alert",JOptionPane.WARNING_MESS
AGE);
 }
 public static void main(String[] args) {
 new OptionPaneExample();
 }
 }
Java JOptionPane Example:
Prashant bhandare

showInputDialog()
 import javax.swing.*;
 public class OptionPaneExample {
 JFrame f;
 OptionPaneExample(){
 f=new JFrame();
 String name=JOptionPane.showInputDialog(f,"Ente
r Name");
 }
 public static void main(String[] args) {
 new OptionPaneExample();
 }
 }
Java JScrollBar
Prashant bhandare

 The object of JScrollbar class is used to add


horizontal and vertical scrollbar.

 It is an implementation of a scrollbar.

 It inherits JComponent class.


Prashant bhandare

Commonly used Constructors:

Constructor Description

Creates a vertical scrollbar with the


JScrollBar()
initial values.

Creates a scrollbar with the specified


JScrollBar(int orientation)
orientation and the initial values.

Creates a scrollbar with the specified


JScrollBar(int orientation, int
orientation, value, extent, minimum, and
value, int extent, int min, int max)
maximum.
Java JScrollBar Example
Prashant bhandare

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

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.

 The object of JMenuItem class adds a simple labeled


menu item.

 The items used in a menu must belong to the


JMenuItem or any of its subclass.
Jmenu example
Prashant bhandare

 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");
 menu.add(i1); menu.add(i2); menu.add(i3);
 submenu.add(i4); submenu.add(i5);
 menu.add(submenu);
 mb.add(menu);
Prashant bhandare

 f.setJMenuBar(mb);
 f.setSize(400,400);
 f.setLayout(null);
 f.setVisible(true);
 }
 public static void main(String args[])
 {
 new MenuExample();
 }
}
Java JPopupMenu
Prashant bhandare

 PopupMenu can be dynamically popped up


at specific position within a component.

 It inherits the JComponent class.

Commonly used Constructors:


Constructor Description

Constructs a JPopupMenu without an


JPopupMenu()
"invoker".

JPopupMenu(String Constructs a JPopupMenu with the specified


label) title.
Java JPopupMenu Example
Prashant bhandare

 import javax.swing.*;
 import java.awt.event.*;
 class PopupMenuExample
 {
 PopupMenuExample(){
 final JFrame f= new JFrame("PopupMenu
Example");
 final JPopupMenu popupmenu = new
JPopupMenu("Edit");
 JMenuItem cut = new JMenuItem("Cut");
 JMenuItem copy = new JMenuItem("Copy");
 JMenuItem paste = new JMenuItem("Paste");
 popupmenu.add(cut); popupmenu.add(copy);
popupmenu.add(paste);
 f.addMouseListener(new MouseAdapter() {
Prashant bhandare

 public void mouseClicked(MouseEvent e) {


 popupmenu.show(f , e.getX(), e.getY());
 }
 });
 f.add(popupmenu);
 f.setSize(300,300);
 f.setLayout(null);
 f.setVisible(true);
 }
 public static void main(String args[])
 {
 new PopupMenuExample();
 }}
Java JSeparator
Prashant bhandare

 The object of JSeparator class is used to


provide a general purpose component for
implementing divider lines.

 It is used to draw a line to separate widgets


in a Layout.

 It inherits JComponent class.


Prashant bhandare

Commonly used Constructors of JSeparator


Constructor Description

JSeparator() Creates a new horizontal separator.

Creates a new separator with the specified


JSeparator(int orientation)
horizontal or vertical orientation.

Commonly used Methods of JSeparator

Method Description
void setOrientation(int It is used to set the orientation of the
orientation) separator.

It is used to return the orientation of the


int getOrientation()
separator.
Java JSeparator Example 1
Prashant bhandare

 import javax.swing.*;
 class SeparatorExample
 {
 JMenu menu, submenu;
 JMenuItem i1, i2, i3, i4, i5;
 SeparatorExample() {
 JFrame f= new JFrame("Separator Example");

 JMenuBar mb=new JMenuBar();


 menu=new JMenu("Menu");
 i1=new JMenuItem("Item 1");
 i2=new JMenuItem("Item 2");
 menu.add(i1);
 menu.addSeparator();
Prashant bhandare

 menu.add(i2);
 mb.add(menu);
 f.setJMenuBar(mb);
 f.setSize(400,400);
 f.setLayout(null);
 f.setVisible(true);
}
 public static void main(String args[])
{
 new SeparatorExample();
 }}
Java JSeparator Example 2
Prashant bhandare

 import javax.swing.*;
 import java.awt.*;
 public class SeparatorExample
 {
 public static void main(String args[]) {
 JFrame f = new JFrame("Separator Example");
 f.setLayout(new GridLayout(0, 1));
 JLabel l1 = new JLabel("Above Separator");
 f.add(l1);
 JSeparator sep = new JSeparator();
 f.add(sep);
 JLabel l2 = new JLabel("Below Separator");
 f.add(l2);
 f.setSize(400, 100);
 f.setVisible(true);
 }
 }
Java JProgressBar
Prashant bhandare

 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.

It is used to create a horizontal progress bar with the specified


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

It is used to create a progress bar with the specified orientation,


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

JProgressBar(int orient, int min, It is used to create a progress bar with the specified orientation,
int max) minimum and maximum value.
Commonly used Methods:
Prashant bhandare

Method Description
void It is used to determine whether string
setStringPainted(boolean b) should be displayed.

It is used to set value to the progress


void setString(String s)
string.

It is used to set the orientation, it may be


either vertical or horizontal by using
void setOrientation(int
SwingConstants.VERTICAL and
orientation)
SwingConstants.HORIZONTAL
constants.

It is used to set the current value on the


void setValue(int value)
progress bar.
Java JProgressBar Example
Prashant bhandare

 import javax.swing.*;
 public class ProgressBarExample extends JFrame{
 JProgressBar jb;
 int i=0,num=0;
 ProgressBarExample(){
 jb=new JProgressBar(0,2000);
 jb.setBounds(40,40,160,30);
 jb.setValue(0);
 jb.setStringPainted(true);
 add(jb);
 setSize(250,150);
 setLayout(null);
 }
Prashant bhandare

 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 JTree
Prashant bhandare

 The JTree class is used to display the tree


structured data or hierarchical data.

 JTree is a complex component. It has a 'root


node' at the top most which is a parent for all
nodes in the tree.

 It inherits JComponent class.


Commonly used Constructors:
Prashant bhandare

Constructor Description

JTree() Creates a JTree with a sample model.

Creates a JTree with every element of the


JTree(Object[] value) specified array as the child of a new root
node.

Creates a JTree with the specified TreeNode


JTree(TreeNode root)
as its root, which displays the root node.
Prashant bhandare
Java JTabbedPane
Prashant bhandare

 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.


Commonly used Constructors:
Constructor Description

Creates an empty TabbedPane with a


JTabbedPane()
default tab placement of JTabbedPane.Top.

Creates an empty TabbedPane with a


JTabbedPane(int tabPlacement)
specified tab placement.

Creates an empty TabbedPane with a


JTabbedPane(int tabPlacement,
specified tab placement and tab layout
int tabLayoutPolicy)
policy.
Java JTabbedPane Example
Prashant bhandare

 import javax.swing.*;
 public class TabbedPaneExample {
 JFrame f;
 TabbedPaneExample(){
 f=new JFrame();
 JTextArea ta=new JTextArea(200,200);
 JPanel p1=new JPanel();
 p1.add(ta);
 JPanel p2=new JPanel();
 JPanel p3=new JPanel();
 JTabbedPane tp=new JTabbedPane();
 tp.setBounds(50,50,200,200);
 tp.add("main",p1);
Prashant bhandare

 tp.add("visit",p2);
 tp.add("help",p3);
 f.add(tp);
 f.setSize(400,400);
 f.setLayout(null);
 f.setVisible(true);
 }
 public static void main(String[] args) {
 new TabbedPaneExample();
 }
 }
JToggleButton
Prashant bhandare

A toggle button is two-states button that


allows user to switch on and off.

 To create a toggle button in Swing you


use JToggleButton class.

 Here are the most common used constructors


of the JToggleButton class:
Prashant bhandare
JToggleButton Constructors Meanings

Creates a toggle button without text and icon.


public JToggleButton( )
The state of toggle button is not selected.

public JToggleButton(Icon icon) Creates a toggle button with icon

Creates a toggle button with icon and initialize


public JToggleButton(Icon icon, boolean
the state of toggle button by the
selected)
boolean parameter selected

public JToggleButton(String text) Creates a toggle button with text

public JToggleButton(String text, boolean Creates a toggle button with text and
selected) initialize the state of the toggle button

Creates a toggle button which displays both


public JToggleButton(String text, Icon icon)
text and icon.

Creates a toggle button which displays both


public JToggleButton(String text, Icon icon,
text and icon. The state of toggle button can be
boolean selected)
initialized.
How to use ToolTip in Java Swing
Prashant bhandare

 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:
Simple ToolTip Example
Prashant bhandare

 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);
 }
 }
Java JSlider
Prashant bhandare

 The Java JSlider class is used to create the


slider.
 By using JSlider, a user can select a value
from a specific range.
Commonly used Constructors of JSlider class
Constructor Description

JSlider() creates a slider with the initial value of 50 and range of 0 to 100.

creates a slider with the specified orientation set by either


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

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

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

JSlider(int orientation, int min, int max,


creates a slider using the given orientation, min, max and value.
int value)
Prashant bhandare

Commonly used Methods of JSlider class


Method Description

is used to set the minor tick spacing to the


public void setMinorTickSpacing(int n)
slider.

is used to set the major tick spacing to the


public void setMajorTickSpacing(int n)
slider.

is used to determine whether tick marks are


public void setPaintTicks(boolean b)
painted.

is used to determine whether labels are


public void setPaintLabels(boolean b)
painted.

is used to determine whether track is


public void setPaintTracks(boolean b)
painted.
Java JSlider Example
Prashant bhandare

 import javax.swing.*;
 public class SliderExample1 extends JFrame{
 public SliderExample1() {
 JSlider slider = new JSlider(JSlider.HORIZONTAL
, 0, 50, 25);
 JPanel panel=new JPanel();
 panel.add(slider);
 add(panel);
 }
 public static void main(String s[]) {
 SliderExample1 frame=new SliderExample1();
 frame.pack();
 frame.setVisible(true);
 }
 }
Java JDialog
Prashant bhandare

 The JDialog control represents a top level


window with a border and a title used to take
some form of input from the user.

 It inherits the Dialog class.

 Unlike JFrame, it doesn't have maximize and


minimize buttons.
Commonly used Constructors:
Prashant bhandare

Constructor Description

It is used to create a modeless dialog without a


JDialog()
title and without a specified Frame owner.

It is used to create a modeless dialog with


JDialog(Frame owner) specified Frame as its owner and an empty
title.

JDialog(Frame owner, String It is used to create a dialog with the specified


title, boolean modal) title, owner Frame and modality.
Java JDialog Example
Prashant bhandare

 import javax.swing.*;
 import java.awt.*;
 import java.awt.event.*;
 public class DialogExample {
 private static JDialog d;
 DialogExample() {
 JFrame f= new JFrame();
 d = new JDialog(f , "Dialog Example", true);
 d.setLayout( new FlowLayout() );
 JButton b = new JButton ("OK");
 b.addActionListener ( new ActionListener()
 {
 public void actionPerformed( ActionEvent e )
 {
 DialogExample.d.setVisible(false);
 }
 });
Prashant bhandare
 d.add( new JLabel ("Click button to
continue."));
 d.add(b);
 d.setSize(300,300);
 d.setVisible(true);
 }
 public static void main(String args[])
 {
 new DialogExample();
 }
 }
Java JPanel
Prashant bhandare

 The JPanel is a simplest container class.

 It provides space in which an application can


attach any other component.

 It inherits the JComponents class.

 It doesn't have title bar.


Prashant bhandare

Commonly used Constructors:


Constructor Description

It is used to create a new JPanel with a


JPanel()
double buffer and a flow layout.

It is used to create a new JPanel with


JPanel(boolean
FlowLayout and the specified buffering
isDoubleBuffered)
strategy.

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


layout) specified layout manager.
Java JFileChooser
Prashant bhandare

 The object of JFileChooser class represents


a dialog window from which the user can
select file.

 It inherits JComponent class.


Commonly used Constructors:
Prashant bhandare

Constructor Description

Constructs a JFileChooser pointing to the user's


JFileChooser()
default directory.

JFileChooser(File Constructs a JFileChooser using the given File as


currentDirectory) the path.

JFileChooser(String
Constructs a JFileChooser using the given path.
currentDirectoryPath)
MVC
Prashant bhandare

 Model : The domain-specific representation


of the information on which the application
op-erates.

 The model is another name for the


application logic layer (sometimes also called
the domain layer).

 Application (or domain) logic adds meaning


to raw data (e.g., calculating if to-day is the
user’s birthday, or the totals, taxes and
shipping charges for shopping cart items).
 View:
Prashant bhandare Renders the model into a form
suitable for interaction, typically a user
interface element.

 MVC is often seen in web applications,


where the view is the HTML page and the
code which gathers dynamic data for the
page.

 Controller : Processes and responds to


events, typically user actions, and may
invoke changes on the model and view.
Prashant bhandare

You might also like