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

AJP Chapter 2

Ajp chapter 2 ppt

Uploaded by

sujalbpatil76
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 views49 pages

AJP Chapter 2

Ajp chapter 2 ppt

Uploaded by

sujalbpatil76
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/ 49

Chapter 2

SWING
Made by
Mrs. Smita Kuldiwar
Date:- 19/07/2020
• Swing is a part of Java Foundation Classes(JFC).
• It is used to develop GUI or window based
application.
• Swing components are platform independent.
• Swing components are lightweight.
• It is used for creating window based applications.
What is Swing? • Swing support pluggable look and feel.
• Swing provides more powerful components such
as tables, lists, scrollpanes, colorchooser and
tabbedpane, etc.
• Swing follows MVC.
• The javax.swing packages provides classes for
java swing API such as JButton, JTextArea,
JTextField, JRadioButton, JMenu, CheckBox etc.
Swing Features
Light weight :- Swing components are independent of native operating
systems API as swing control are rendered mostly using pure java code instead
of underlying operating system calls.

Rich Controls:- Swing provides a rich set of advanced controls like tree,
tabbedpane, slider colorpicker, table controls etc.

Highly Customizable:- Swing controls can be customized in very easy ways


visual appearance is independent of internal representation.

Pluggable Look and Feel:- Swing based GUI applications look and feel can be
changed at run time based on available values.
• Swing provides both additional components and
added functionality to AWT-replacement
components
• Swing components can change their appearance
based on the current "look and feel" library that's
being used.
• You can use the same look and feel as the platform
Advantages of you're on, or use a different look and feel
• Swing components follow the
Swing Model-View-Controller paradigm (MVC), and thus
can provide a much more flexible UI.
•Swing provides "extras" for components, such as:
• Icons on many components
• Decorative borders for components
• Tooltips for components
• Swing components are lightweight (less resource
intensive than AWT)
Difference Between AWT and Swing

AWT SWING
• Platform Dependent • Platform Independent

• Does not follow MVC • Follows MVC

• Lesser Components • More powerful Components

• Does not support • Supports pluggable look and


pluggable look and feel feel

• Heavyweight • Lightweight
Java Swing
Class
Hierarchy
• All the components in swing like JButton,
JComboBox, JList, JLabel are inherited from
the JComponent class which can be added to
the container classes.
Explanation: • Containers are the windows like frame and
dialog boxes.
• Containers like JFrame and JDialog can only
add a component to itself.
• 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
Container classes:
• Panel – It is used to organize components
Class on to a window
• Frame – A fully functioning window with
icons and titles
• Dialog – It is like a pop up window but not
fully functional like the frame.
Swing Components
• 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.
• 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.
• JTextField:- The object of a JTextField class is a text component that allows the
editing of a single line text.
• JTextArea:- The object of a JTextArea class is a multi line region that displays text.
It allows the editing of multiple line text.
• JCheckBox:-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 ".
• 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.
Swing Components cont…
• JComboBox :-The object of Choice class is used to show popup menu of choices. Choice
selected by user is shown on the top of a menu.
• 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.
• JTable :-The JTable class is used to display data in tabular form. It is composed of rows
and columns.
• JTabbedPane:-The JTabbedPane class is used to switch between a group of components
by clicking on a tab with a given title or icon.
• JProgressBar:- The JProgressBar class is used to display the progress of the task.
• Jtree:- 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 topmost which is a parent for all
nodes in the tree.
• JScrollPane:- A JscrollPane is used to make scrollable view of a component. When screen
size is limited, we use a scroll pane to display a large component or a component whose
size can change dynamically.
• JToolTip:- When the cursor enters the boundary of that component a popup appears,
and text is displayed. We can create a tool tip for any Jcomponent with
setToolTipText() method. This method is used to set up a tool tip for the component.
Link for chapter 1 quiz
• https://quizizz.com/join/quiz/5f108c2a73afd2001defcda8/start?stud
entShare=true
MVC Architecture
What is MVC Architecture in Java?
• Model designs based on MVC architecture follow the MVC design pattern and
they separate the application logic from the user interface when designing
software. As the name implies MVC pattern has three layers, which are:
• Model – Represents the business layer of the application.
• View – Defines the presentation of the application.
• Controller – Manages the flow of the application.
MVC Architecture cont…
• In Java Programming context, the Model consists of simple Java classes, the View
displays the data and the Controller consists of servlets. This separation results in
user requests being processed as follows:
• The browser on the client sends a request for a page to the controller present on
the server.
• The controller performs the action of invoking the model, thereby, retrieving the
data it needs in response to the request.
• The controller then gives the retrieved data to the view.
• The view is rendered and sent back to the client for the browser to display
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.

Constructor Description
JFrame() It constructs a new frame that is
initially invisible.
JFrame(GraphicsConfiguration gc) It creates a Frame in the specified
Graphics Configuration of a screen
device and a blank title.
JFrame(String title) It creates a new, initially invisible
Frame with the specified title.
JFrame(String title, It creates a JFrame with the specified
GraphicsConfiguration gc) title and the specified Graphics
Configuration of a screen device.
JFrame 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");
JButton button = new JButton();
button.setText("Button");
JFrame Example cont…
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);
}
}
JComponent Example
import java.awt.Color;
import java.awt.Graphics; OUTPUT:-
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyJComponent extends JComponent {
public void paint(Graphics g) {
g.setColor(Color.green);
g.fillRect(30, 30, 100, 100);
}
}
JComponent Example cont…
public class JComponentExample {
public static void main(String[] arguments) {
MyJComponent com = new MyJComponent();
// create a basic JFrame
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JComponent Example");
frame.setSize(300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the JComponent to main frame
frame.add(com);
frame.setVisible(true);
}
}
JButton Example
import javax.swing.*; OUTPUT
public class example{
public static void main(String args[]) {
JFrame f = new JFrame("example");
JButton b = new JButton("click me");
b.setBounds(40,90,85,20);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Jlabel:- Common constructors and methods
Constructor Description Methods Description

JLabel() Creates a JLabel String getText() It returns the text


instance with no string that a label
image and with an displays.
empty string for the
void setText(String It defines the single
title.
text) line of text this
JLabel(String s) Creates a JLabel component will display.
instance with the
specified text. void It sets the alignment of
setHorizontalAlignment the label's contents
JLabel(Icon i) Creates a JLabel (int alignment) along the X axis.
instance with the
specified image. Icon getIcon() It returns the graphic
image that the label
JLabel(String s, Icon i, Creates a JLabel displays.
int instance with the
horizontalAlignment) specified text, image, int It returns the
and horizontal getHorizontalAlignment alignment of the label's
alignment. () contents along the X
axis.
JLabel Example
import javax.swing.*;
class LabelExample OUTPUT:-
{
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,0);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
JTextField:- 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


columns) the specified text and columns.

JTextField(int columns) Creates a new empty TextField with


the specified number of columns.
JTextField Example
import javax.swing.*;
class TextFieldExample OUTPUT:-
{
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);
} }
JTextArea
Commonly used Constructors and Commonly used Methods:
Constructor Description Methods Description

JTextArea() Creates a text area that void setRows(int It is used to set


displays no text initially. rows) specified number of
rows.
JTextArea(String s) Creates a text area that void setColumns(int It is used to set
displays specified text cols) specified number of
initially. columns.

JTextArea(int row, Creates a text area with void setFont(Font f) It is used to set the
int column) the specified number of specified font.
rows and columns that void insert(String s, It is used to insert
displays no text initially. int position) the specified text on
the specified
JTextArea(String s, Creates a text area with position.
int row, int column) the specified number of
rows and columns that void append(String s) It is used to append
displays specified text. the given text to the
end of the document.
JTextArea Example
import javax.swing.*;
public class TextAreaExample
{ OUTPUT:-
TextAreaExample(){
Frame 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();
}
}
JCheckBox
• Commonly used Constructors:
Constructor Description

JCheckBox() 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 text, Creates a check box with text and specifies


boolean selected) whether or not it is initially selected.

JCheckBox(Action a) Creates a check box where properties are


taken from the Action supplied.
JCheckBox Example
import javax.swing.*;
public class CheckBoxExample
{ OUTPUT:-
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();
}}
JRadioButton
• Commonly used Constructors and Methods:-
Constructor Description Methods Description

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


JRadioButton() Creates an unselected on button.
radio button with no
text. String getText() It is used to return the text of
the button.
JRadioButton(String s) Creates an unselected
void setEnabled(boolean It is used to enable or disable
radio button with
b) the button.
specified text.
JRadioButton(String s, Creates a radio button void setIcon(Icon b) It is used to set the specified
Icon on the button.
boolean selected) with the specified
text and selected Icon getIcon() It is used to get the Icon of
status. the button.
JRadioButton Example
import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){ OUTPUT:-
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();
JComboBox
Commonly used Constructors and Methods:-
Methods Description
Constructor Description
void addItem(Object anObject) It is used to add an item to the
item list.
JComboBox() Creates a JComboBox
with a default data model. void removeItem(Object It is used to delete an item to
anObject) the item list.

JComboBox(Object[] Creates a JComboBox void removeAllItems() It is used to remove all the


items from the list.
items) that contains the elements
in the specified array. void setEditable(boolean b) It is used to determine whether
the JComboBox is editable.
void It is used to add
JComboBox(Vector<?> Creates a JComboBox addActionListener(ActionListe the ActionListener.
items) that contains the elements ner a)
in the specified Vector.
void It is used to add
addItemListener(ItemListener i) the ItemListener.
JComboBox Example
import javax.swing.*;
public class ComboBoxExample {
JFrame f; OUTPUT:-
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();
} }
JList
• Commonly used Constructors and Methods:-
Constructor Description Methods Description

Void It is used to add a


JList() Creates a JList addListSelectionListener( listener to the list, to be
with an empty, ListSelectionListener notified each time a
read-only, model. listener) change to the selection
occurs.
JList(ary[] Creates a JList int getSelectedIndex() It is used to return the
listData) that displays the smallest selected cell
elements in the index.
specified array.
ListModel getModel() It is used to return the
data model that holds a
list of items displayed by
JList(ListModel<ar Creates a JList the JList component.
y> dataModel) that displays
elements from the void setListData(Object[] It is used to create a
specified, listData) read-only ListModel from
non-null, model. an array of objects.
JList Example
import javax.swing.*;
public class ListExample
{
ListExample(){ OUTPUT :-
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]) {
new ListExample(); }}
Java JTable
• Commonly used Constructors and Methods:-

Constructor Description

JTable() Creates a table with empty


cells.

JTable(Object[][] rows, Creates a table with the


Object[] columns) specified data.
Java JTable Example
import javax.swing.*;
public class TableExample {
JFrame f; OUTPUT:-
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 JTabbedPane
• 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.
Java JTabbedPane Example
import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){ output
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200); tp.add("main",p1);
tp.add("visit",p2); tp.add("help",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); }
public static void main(String[] args) {
new TabbedPaneExample();
}}
Java JProgressBar
• Commonly used Constructors and Methods:-
Constructor Description Method Description
JProgressBar() It is used to create a
void It is used to determine
horizontal progress bar but no
string text.
setStringPainted(bool whether string should
ean b) be displayed.
JProgressBar(int min, int It is used to create a
max) horizontal progress bar with void setString(String It is used to set value
the specified minimum and s) to the progress string.
maximum value.
void setOrientation(int It is used to set the
JProgressBar(int orient) It is used to create a progress
orientation) orientation, it may be
bar with the specified
orientation, it can be either
either vertical or
Vertical or Horizontal by using horizontal by using
SwingConstants.VERTICAL SwingConstants.VERTIC
and AL and
SwingConstants.HORIZONTAL SwingConstants.HORIZ
constants. ONTAL constants.
JProgressBar(int orient, It is used to create a progress
int min, int max) bar with the specified
void setValue(int It is used to set the
orientation, minimum and value) current value on the
maximum value. progress bar.
Java JProgressBar Example
import javax.swing.*;
public class ProgressBarExample extends Jframe
{
JProgressBar jb;
int i=0,num=0;
ProgressBarExample()
{
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(250,150);
setLayout(null);
}
Java JProgressBar Example
public void iterate()
{ while(i<=2000)
{ OUTPUT:
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
Constructor Description

JTree() Creates a JTree with a sample model.

JTree(Object[] value) Creates a JTree with every element of


the specified array as the child of a new
root node.

JTree(TreeNode root) Creates a JTree with the specified


TreeNode as its root, which displays the
root node.
Java JTree Example
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color); style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
Java JTree Example Cont…
color.add(red);
color.add(blue);
color.add(black); OUTPUT
color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}
JScrollPane
Common Constructors

Constructor Purpose

JScrollPane() It creates a scroll pane. The


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

JScrollPane(Component, int, int)


JScrollPane Example
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
public class JScrollPaneExample
{
private static final long serialVersionUID = 1L;
private static void createAndShowGUI()
{
final JFrame frame = new JFrame("Scroll Pane Example");
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
JScrollPane Example
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollableTextArea = new JScrollPane(textArea);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
OUTPUT
ToolTip Example
import javax.swing.*;
public class ToolTipExample { OUTPUT:-
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
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);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}

You might also like