SlideShare ist ein Scribd-Unternehmen logo
1 von 49
Prepared by:-Jaydeep R.Viradiya
Asst Prof
Parul University,Baroda
1
Swing in java
Unit -1
The Abstract Windowing Toolkit
2
Since Java was first released, its user interface
facilities have been a significant weakness
The Abstract Windowing Toolkit (AWT) was part of the
JDK form the beginning, but it really was not sufficient
to support a complex user interface
JDK 1.1 fixed a number of problems, and most
notably, it introduced a new event model. It did
not make any major additions to the basic
components
Java Foundation Classes
3
In April 1997, JavaSoft announced the Java
Foundation Classes (JFC).
a major part of the JFC is a new set of user interface
components called Swing.
AWT Swing Accessibility
Java
2D
Drag
And
Drop
Swing
4
The Swing classes are used to build GUIs
Swing does not stand for anything
Swing is built on top of the 1.1/1.2 AWT libraries
Swing makes 3 major improvements on the AWT
does not rely on the platform’s native components
it supports “Pluggable Look-and-Feel” or PLAF
it is based on the Model-View-Controller (MVC)
AWT
Swing
JFC
JDK 1.2
GUI Packages
5
AWT
java.awt
java.awt.color
java.awt.datatransfer
java.awt.event
java.awt.font
java.awt.geom
java.awt.image
...
Swing
javax.accessibility
javax.swing
javax.swing.colorchooser
javax.swing.event
javax.swing.filechooser
javax.swing.plaf
javax.swing.table
javax.swing.text.html
javax.swing.tree
...
Components
6
A GUI consists of different graphic Component
objects which are combined into a hierarchy using
Container objects.
Component class
An abstract class for GUI components such as menus,
buttons, labels, lists, etc.
Container
An abstract class that extends Component. Containers
can hold multiple components.
Weighing Components
7
Sun makes a distinction between lightweight and
heavyweight components
Lightweight components are not dependent on native
peers to render themselves. They are coded in Java.
Heavyweight components are rendered by the host
operating system. They are resources managed by the
underlying window manager.
Heavyweight Components
8
Heavyweight components were unwieldy for two
reasons
Equivalent components on different platforms do not
necessarily act alike.
The look and feel of each component was tied to the host
operating system
Almost all Swing components are lightweight except
JApplet, JFrame, JDialog, and JWindow
Additional Swing Features
9
Swing also provides
A wide variety of components (tables, trees, sliders, progress
bars, internal frame, …)
Swing components can have tooltips placed over them.
Arbitrary keyboard events can be bound to components.
Additional debugging support.
Support for parsing and displaying HTML based information.
Applets versus Applications
10
Using Swing it is possible to create two different types of
GUI programs
Standalone applications
Programs that are started from the command line
Code resides on the machine on which they are run
Applets
Programs run inside a web browser
Code is downloaded from a web server
JVM is contained inside the web browser
For security purposes Applets are normally prevented from doing certain
things (for example opening files)
For now we will write standalone applications
Three Types of GUI Classes
11
1. Containers
JFrame, JPanel, JApplet
1. Components
JButton, JTextField, JComboBox, JList, etc.
1. Helpers
Graphics, Color, Font, Dimension, etc.
JFrames
12
A JFrame is a Window with all of the adornments added.
JFrame inherits from Frame, Window,
Container, Component, and Object
A JFrame provides the basic building block for screen-
oriented applications.
JFrame win = new JFrame( “title” );
Creating a JFrame
13
import javax.swing.*;
public class SwingFrame {
public static void main( String args[] ) {
JFrame win = new JFrame( "My First GUI Program" );
win.setVisible(true);
}
} // SwingFrame
JFrame
14
Sizing a Frame
You can specify the size
Height and width given in pixels
The size of a pixel will vary based on the resolution of the device on
which the frame is rendered
Usually one uses an instance of the Dimension class.
The method pack() will set the size of the frame
automatically, based on the size of the components contained in
the content pane
Note that pack does not look at the title bar
Sometimes pack() does not work as you might expect; try it and see.
Creating a JFrame
15
import javax.swing.*;
import java.awt.*;
public class SwingFrame {
static Dimension windowSize = new Dimension( 250, 150 );
public static void main( String args[] ) {
JFrame win = new JFrame( "My First GUI Program" );
win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
win.setSize( windowSize );
win.setVisible(true);
}
} // SwingFrame
Swing Components
16
JComponent
JComboBox, JLabel, JList, JMenuBar,
JPanel, JPopupMenu, JScrollBar,
JScrollPane, JTable, JTree,
JInternalFrame, JOptionPane,
JProgressBar, JRootPane, JSeparator,
JSlider, JSplitPane, JTabbedPane,
JToolBar, JToolTip, Jviewport,
JColorChooser, JTextComponent, …
JLabels
17
JLabels are components that you can fill with text.
When creating a label you can specify the initial value and
the alignment you wish to use within the label.
You can use getText() and setText() to get and
change the value of the label.
lbl = new JLabel( ”text", JLabel.RIGHT );
Hello World
18
import javax.swing.*;
public class SwingFrame {
public static void main( String args[] ) {
JFrame win = new JFrame( "My First GUI Program" );
JLabel label = new JLabel( "Hello World" );
win.getContentPane().add( label );
win.setVisible(true);
}
} // SwingFrame
JButtons
19
JButton extends Component , displays a string, and
delivers an ActionEvent for each mouse click.
Normally buttons are displayed with a border
In addition to text, JButtons can also display icons
button = new JButton( ”text“ );
Buttons
20
import javax.swing.*;
public class SwingFrame {
public static void main( String args[] ) {
JFrame win = new JFrame( "My First GUI Program" );
JButton button = new JButton( "Click Me!!" );
win.getContentPane().add( button );
win.setVisible(true);
}
} // SwingFrame
Layout Manager
21
Layout Manager
An interface that defines methods for positioning and sizing
objects within a container. Java defines several default
implementations of LayoutManager.
Geometrical placement in a Container is controlled by a
LayoutManager object
Components, Containers, and Layout
Managers
22
Containers may contain components (which means
containers can contain containers!!).
All containers come equipped with a layout manager which
positions and shapes (lays out) the container's components.
Much of the action in Swing occurs between components,
containers, and their layout managers.
Layout Managers
23
Layouts allow you to format components on the screen
in a platform-independent way
The standard JDK provides many classes that implement
the LayoutManager interface, including:
FlowLayout
GridLayout
BorderLayout
BoxLayout
Changing the Layout
24
1. To change the layout used in a container you first need
to create the layout.
2. Then you invoke the setLayout() method on the
container to use the new layout.
 The layout manager should be established before any
components are added to the container
JPanel p = new JPanel() ;
p.setLayout( new FlowLayout() );
FlowLayout
25
FlowLayout is the default layout for the JPanel
class.
When you add components to the screen, they flow left
to right (centered) based on the order added and the
width of the screen.
Very similar to word wrap and full justification on a
word processor.
If the screen is resized, the components' flow will
change based on the new width and height
Flow Layout
26
import javax.swing.*;
import java.awt.*;
public class ShowFlowLayout {
public static void main( String args[] ) {
JFrame win = new JFrame( "My First GUI Program" );
win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
win.getContentPane().setLayout( new FlowLayout() );
for ( int i = 0; i < 10; i++ ) {
win.getContentPane().add(
new JButton( String.valueOf( i ) ) );
}
win.setVisible(true);
}
} // ShowFlowLayout
FlowLayout
27
GridLayout
28
Arranges components in rows and columns
If the number of rows is specified
columns = number of components / rows
If the number of columns is specified
Rows = number of components / columns
The number of columns is ignored unless the number of rows
is zero.
The order in which you add components matters
Component 1  (0,0), Component 2  (0,1), …...
Components are resized to fit the row-column area
Grid Layout
29
import javax.swing.*;
import java.awt.*;
public class ShowGridLayout {
public static void main( String args[] ) {
JFrame win = new JFrame( "My First GUI Program" );
win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
win.getContentPane().setLayout( new GridLayout( 2, 0 ) );
for ( int i = 0; i < 10; i++ ){
win.getContentPane().add(
new JButton( String.valueOf( i ) ) );
}
win.setVisible(true);
}
} // ShowGridLayout
GridLayout
30
gridLayout( 2, 4 )
gridLayout( 0, 4 ) gridLayout( 4, 4 ) gridLayout( 10, 10 )
BoxLayout
31
BoxLayout provides an easy way to lay out components
horizontally or vertically.
Components are added in order.
BoxLayout attempts to arrange components at their
preferred widths (for horizontal layout) or
preferred heights (for vertical layout).
BoxLayout example
32
import javax.swing.*;
import java.awt.*;
public class ShowBoxLayout {
public static void main( String args[] ) {
JFrame win = new JFrame( "My First GUI Program" );
win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
win.getContentPane().setLayout(
new BoxLayout( win.getContentPane(), BoxLayout.X_AXIS ) );
for ( int i = 0; i < 10; i++ ){
win.getContentPane().add( new JButton( String.valueOf( i ) ) );
win.getContentPane().add( Box.createHorizontalGlue() );
}
win.pack();
win.setVisible(true);
}
} // ShowBoxLayout
BoxLayout
33
Note that components retain their preferred size.
BorderLayout
34
BorderLayout provides 5 areas to hold
components. These are named after the four different
borders of the screen, North, South, East, West, and
Center.
When a Component is added to the layout, you must
specify which area to place it in. The order in which
components are added is not important.
The center area will always be resized to be as large as
possible
BorderLayout
35
import javax.swing.*;
import java.awt.*;
public class ShowBorderLayout {
public static void main( String args[] ) {
JFrame win = new JFrame( "My First GUI Program" );
win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
Container content = win.getContentPane();
content.setLayout( new BorderLayout() );
content.add( BorderLayout.NORTH, new JButton( "North" ) );
content.add( "South", new JButton( "South" ) );
content.add( "East", new JButton( "East" ) );
content.add( "West", new JButton( "West" ) );
content.add( "Center", new JButton( "Center" ) );
win.setVisible(true);
}
} // ShowBorderLayout
BorderLayout
36
Containers
37
A JFrame is not the only type of container that you
can use in Swing
The subclasses of Container are:
JPanel
JWindow
JApplet
Window is subclassed as follows:
JDialog
JFrame
38
Making components active
Most components already appear to do something--buttons click,
text appears
To associate an action with a component, attach a listener to it
Components send events, listeners listen for events
Different components may send different events, and require
different listeners
39
Listeners
Listeners are interfaces, not classes
class MyButtonListener implements
ActionListener {
An interface is a group of methods that must be supplied
When you say implements, you are promising to supply those
methods
40
Writing a Listener
For a Button, you need an ActionListener
b1.addActionListener
(new MyButtonListener ( ));
An ActionListener must have an
actionPerformed(ActionEvent) method
public void actionPerformed(ActionEvent e) {
…
}
41
MyButtonListener
public void init () {
...
b1.addActionListener (new MyButtonListener ());
}
class MyButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
showStatus ("Ouch!");
}
}
42
Listeners for TextFields
An ActionListener listens for someone hitting the Enter key
An ActionListener requires this method:
public void actionPerformed (ActionEvent e)
You can use getText( ) to get the text
A TextListener listens for any and all keys
A TextListener requires this method:
public void textValueChanged(TextEvent e)
43
Summary I: Building a GUI
Create a container, such as Frame or Applet
Choose a layout manager
Create more complex layouts by adding Panels; each Panel can
have its own layout manager
Create other components and add them to whichever Panels
you like
44
Vocabulary
AWT – The Abstract Window Toolkit provides basic graphics
tools (tools for putting information on the screen)
Swing – A much better set of graphics tools
Container – a graphic element that can hold other graphic
elements (and is itself a Component)
Component – a graphic element (such as a Button or a
TextArea) provided by a graphics toolkit
listener – A piece of code that is activated when a particular kind
of event occurs
layout manager – An object whose job it is to arrange
Components in a Container
A Simple 4 Function Calculator
45
Swing Components
46
JFrame
with BorderLayout
JButton
JLabel
JPanel
with GridLayout
CalcGui.java (pg. 1)
47
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CalcGui {
// Labels for the buttons
private static final String labels = "789X456/123-0C=+";
private static final int NUMROWS = 4;
private static final int NUMCOLS = 4;
private JLabel display; // The display
public CalcGui( String name ) {
// A Frame for the calculator
JFrame win = new JFrame(name);
CalcGui.java (pg. 2)
48
// Create the button panel
JPanel buttons = new JPanel();
buttons.setLayout(new GridLayout(NUMROWS, NUMCOLS));
JButton b;
for ( int i = 0 ; i < labels.length() ; i++ ) {
b = new JButton( labels.substring( i, i + 1 ) );
buttons.add( b );
}
// Create the display
display = new JLabel( "0", JLabel.RIGHT );
display.setFont( new Font( "Courier", Font.BOLD, 24 ) );
CalcGui.java (pg. 3)
49
// "Assemble" the calculator
Container content = win.getContentPane();
content.setLayout( new BorderLayout() );
content.add( "North", display );
content.add( "Center", buttons );
// Display it and let the user run with it :-)
win.pack();
win.setVisible(true);
}

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Java Collections
Java  Collections Java  Collections
Java Collections
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
Java Swing
Java SwingJava Swing
Java Swing
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Awt controls ppt
Awt controls pptAwt controls ppt
Awt controls ppt
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
Java Swing
Java SwingJava Swing
Java Swing
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Java awt
Java awtJava awt
Java awt
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Event handling
Event handlingEvent handling
Event handling
 
Core java
Core java Core java
Core java
 
Java keywords
Java keywordsJava keywords
Java keywords
 

Andere mochten auch

67+68 M5C3 Lezione 2. dalla medicalizzazione all inserimento
67+68 M5C3 Lezione 2. dalla medicalizzazione all inserimento67+68 M5C3 Lezione 2. dalla medicalizzazione all inserimento
67+68 M5C3 Lezione 2. dalla medicalizzazione all inserimentoraffaelebruno1
 
5 transformational leadership as jazz
5 transformational leadership as jazz5 transformational leadership as jazz
5 transformational leadership as jazzmikegggg
 
Defining the Human Capital Leader of Tomorrow.doc
Defining the Human Capital Leader of Tomorrow.docDefining the Human Capital Leader of Tomorrow.doc
Defining the Human Capital Leader of Tomorrow.docmikegggg
 
Analysis on the Power Equipment Industry
Analysis on the Power Equipment IndustryAnalysis on the Power Equipment Industry
Analysis on the Power Equipment IndustryHarini Audisekar
 
IT-Projektledelse-JacobN
IT-Projektledelse-JacobNIT-Projektledelse-JacobN
IT-Projektledelse-JacobNJacob Nørgaard
 
Synopsis comprehensive creativewriting
Synopsis comprehensive creativewritingSynopsis comprehensive creativewriting
Synopsis comprehensive creativewritingNasrullah Dharejo
 
Minicurso Iniciando no Mundo Front-End - Dia 05 - SASPI {5}
Minicurso Iniciando no Mundo Front-End - Dia 05 - SASPI {5}Minicurso Iniciando no Mundo Front-End - Dia 05 - SASPI {5}
Minicurso Iniciando no Mundo Front-End - Dia 05 - SASPI {5}Matheus Thomaz
 
Artistas fav.
Artistas fav.Artistas fav.
Artistas fav.gamabeye
 
Ibs business school, pune presents international conference on social media r...
Ibs business school, pune presents international conference on social media r...Ibs business school, pune presents international conference on social media r...
Ibs business school, pune presents international conference on social media r...IBS_Business_School
 
Drupal commerce checkout for the Ukrainian market
Drupal commerce checkout for the Ukrainian marketDrupal commerce checkout for the Ukrainian market
Drupal commerce checkout for the Ukrainian marketAndriy Yun
 

Andere mochten auch (19)

java2 swing
java2 swingjava2 swing
java2 swing
 
ORCID UGent
ORCID UGentORCID UGent
ORCID UGent
 
Certificates
CertificatesCertificates
Certificates
 
Que son los blogs
Que son los blogsQue son los blogs
Que son los blogs
 
Academy Recent
Academy RecentAcademy Recent
Academy Recent
 
67+68 M5C3 Lezione 2. dalla medicalizzazione all inserimento
67+68 M5C3 Lezione 2. dalla medicalizzazione all inserimento67+68 M5C3 Lezione 2. dalla medicalizzazione all inserimento
67+68 M5C3 Lezione 2. dalla medicalizzazione all inserimento
 
5 transformational leadership as jazz
5 transformational leadership as jazz5 transformational leadership as jazz
5 transformational leadership as jazz
 
Defining the Human Capital Leader of Tomorrow.doc
Defining the Human Capital Leader of Tomorrow.docDefining the Human Capital Leader of Tomorrow.doc
Defining the Human Capital Leader of Tomorrow.doc
 
Latest
LatestLatest
Latest
 
Analysis on the Power Equipment Industry
Analysis on the Power Equipment IndustryAnalysis on the Power Equipment Industry
Analysis on the Power Equipment Industry
 
IT-Projektledelse-JacobN
IT-Projektledelse-JacobNIT-Projektledelse-JacobN
IT-Projektledelse-JacobN
 
Synopsis comprehensive creativewriting
Synopsis comprehensive creativewritingSynopsis comprehensive creativewriting
Synopsis comprehensive creativewriting
 
El cerebro
El  cerebroEl  cerebro
El cerebro
 
Minicurso Iniciando no Mundo Front-End - Dia 05 - SASPI {5}
Minicurso Iniciando no Mundo Front-End - Dia 05 - SASPI {5}Minicurso Iniciando no Mundo Front-End - Dia 05 - SASPI {5}
Minicurso Iniciando no Mundo Front-End - Dia 05 - SASPI {5}
 
Artistas fav.
Artistas fav.Artistas fav.
Artistas fav.
 
River Rafting Rishikesh
River Rafting RishikeshRiver Rafting Rishikesh
River Rafting Rishikesh
 
Ibs business school, pune presents international conference on social media r...
Ibs business school, pune presents international conference on social media r...Ibs business school, pune presents international conference on social media r...
Ibs business school, pune presents international conference on social media r...
 
Drupal commerce checkout for the Ukrainian market
Drupal commerce checkout for the Ukrainian marketDrupal commerce checkout for the Ukrainian market
Drupal commerce checkout for the Ukrainian market
 
UOY
UOYUOY
UOY
 

Ähnlich wie Swing

Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892renuka gavli
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1PRN USM
 
Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics ProgrammingRiccardo Cardin
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)Narayana Swamy
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.pptTabassumMaktum
 
The java swing_tutorial
The java swing_tutorialThe java swing_tutorial
The java swing_tutorialsumitjoshi01
 
java presentation on Swings chapter java presentation on Swings
java presentation on Swings chapter java presentation on Swingsjava presentation on Swings chapter java presentation on Swings
java presentation on Swings chapter java presentation on SwingsMohanYedatkar
 
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)Fafadia Tech
 

Ähnlich wie Swing (20)

L11cs2110sp13
L11cs2110sp13L11cs2110sp13
L11cs2110sp13
 
Chap1 1 1
Chap1 1 1Chap1 1 1
Chap1 1 1
 
Chap1 1.1
Chap1 1.1Chap1 1.1
Chap1 1.1
 
Swing
SwingSwing
Swing
 
Swing
SwingSwing
Swing
 
Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892Swingpre 150616004959-lva1-app6892
Swingpre 150616004959-lva1-app6892
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics Programming
 
swingbasics
swingbasicsswingbasics
swingbasics
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)
 
Gui
GuiGui
Gui
 
swings.pptx
swings.pptxswings.pptx
swings.pptx
 
GUI design using JAVAFX.ppt
GUI design using JAVAFX.pptGUI design using JAVAFX.ppt
GUI design using JAVAFX.ppt
 
The java swing_tutorial
The java swing_tutorialThe java swing_tutorial
The java swing_tutorial
 
The java rogramming swing _tutorial for beinners(java programming language)
The java rogramming swing _tutorial for beinners(java programming language)The java rogramming swing _tutorial for beinners(java programming language)
The java rogramming swing _tutorial for beinners(java programming language)
 
14a-gui.ppt
14a-gui.ppt14a-gui.ppt
14a-gui.ppt
 
java presentation on Swings chapter java presentation on Swings
java presentation on Swings chapter java presentation on Swingsjava presentation on Swings chapter java presentation on Swings
java presentation on Swings chapter java presentation on Swings
 
SWING.pptx
SWING.pptxSWING.pptx
SWING.pptx
 
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)J2ME Lwuit, Storage & Connections (Ft   Prasanjit Dey)
J2ME Lwuit, Storage & Connections (Ft Prasanjit Dey)
 
SwingApplet.pptx
SwingApplet.pptxSwingApplet.pptx
SwingApplet.pptx
 

Kürzlich hochgeladen

FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaOmar Fathy
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...soginsider
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfRagavanV2
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projectssmsksolar
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoordharasingh5698
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 

Kürzlich hochgeladen (20)

Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 

Swing

  • 1. Prepared by:-Jaydeep R.Viradiya Asst Prof Parul University,Baroda 1 Swing in java Unit -1
  • 2. The Abstract Windowing Toolkit 2 Since Java was first released, its user interface facilities have been a significant weakness The Abstract Windowing Toolkit (AWT) was part of the JDK form the beginning, but it really was not sufficient to support a complex user interface JDK 1.1 fixed a number of problems, and most notably, it introduced a new event model. It did not make any major additions to the basic components
  • 3. Java Foundation Classes 3 In April 1997, JavaSoft announced the Java Foundation Classes (JFC). a major part of the JFC is a new set of user interface components called Swing. AWT Swing Accessibility Java 2D Drag And Drop
  • 4. Swing 4 The Swing classes are used to build GUIs Swing does not stand for anything Swing is built on top of the 1.1/1.2 AWT libraries Swing makes 3 major improvements on the AWT does not rely on the platform’s native components it supports “Pluggable Look-and-Feel” or PLAF it is based on the Model-View-Controller (MVC) AWT Swing JFC JDK 1.2
  • 6. Components 6 A GUI consists of different graphic Component objects which are combined into a hierarchy using Container objects. Component class An abstract class for GUI components such as menus, buttons, labels, lists, etc. Container An abstract class that extends Component. Containers can hold multiple components.
  • 7. Weighing Components 7 Sun makes a distinction between lightweight and heavyweight components Lightweight components are not dependent on native peers to render themselves. They are coded in Java. Heavyweight components are rendered by the host operating system. They are resources managed by the underlying window manager.
  • 8. Heavyweight Components 8 Heavyweight components were unwieldy for two reasons Equivalent components on different platforms do not necessarily act alike. The look and feel of each component was tied to the host operating system Almost all Swing components are lightweight except JApplet, JFrame, JDialog, and JWindow
  • 9. Additional Swing Features 9 Swing also provides A wide variety of components (tables, trees, sliders, progress bars, internal frame, …) Swing components can have tooltips placed over them. Arbitrary keyboard events can be bound to components. Additional debugging support. Support for parsing and displaying HTML based information.
  • 10. Applets versus Applications 10 Using Swing it is possible to create two different types of GUI programs Standalone applications Programs that are started from the command line Code resides on the machine on which they are run Applets Programs run inside a web browser Code is downloaded from a web server JVM is contained inside the web browser For security purposes Applets are normally prevented from doing certain things (for example opening files) For now we will write standalone applications
  • 11. Three Types of GUI Classes 11 1. Containers JFrame, JPanel, JApplet 1. Components JButton, JTextField, JComboBox, JList, etc. 1. Helpers Graphics, Color, Font, Dimension, etc.
  • 12. JFrames 12 A JFrame is a Window with all of the adornments added. JFrame inherits from Frame, Window, Container, Component, and Object A JFrame provides the basic building block for screen- oriented applications. JFrame win = new JFrame( “title” );
  • 13. Creating a JFrame 13 import javax.swing.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); win.setVisible(true); } } // SwingFrame
  • 14. JFrame 14 Sizing a Frame You can specify the size Height and width given in pixels The size of a pixel will vary based on the resolution of the device on which the frame is rendered Usually one uses an instance of the Dimension class. The method pack() will set the size of the frame automatically, based on the size of the components contained in the content pane Note that pack does not look at the title bar Sometimes pack() does not work as you might expect; try it and see.
  • 15. Creating a JFrame 15 import javax.swing.*; import java.awt.*; public class SwingFrame { static Dimension windowSize = new Dimension( 250, 150 ); public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); win.setSize( windowSize ); win.setVisible(true); } } // SwingFrame
  • 16. Swing Components 16 JComponent JComboBox, JLabel, JList, JMenuBar, JPanel, JPopupMenu, JScrollBar, JScrollPane, JTable, JTree, JInternalFrame, JOptionPane, JProgressBar, JRootPane, JSeparator, JSlider, JSplitPane, JTabbedPane, JToolBar, JToolTip, Jviewport, JColorChooser, JTextComponent, …
  • 17. JLabels 17 JLabels are components that you can fill with text. When creating a label you can specify the initial value and the alignment you wish to use within the label. You can use getText() and setText() to get and change the value of the label. lbl = new JLabel( ”text", JLabel.RIGHT );
  • 18. Hello World 18 import javax.swing.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); JLabel label = new JLabel( "Hello World" ); win.getContentPane().add( label ); win.setVisible(true); } } // SwingFrame
  • 19. JButtons 19 JButton extends Component , displays a string, and delivers an ActionEvent for each mouse click. Normally buttons are displayed with a border In addition to text, JButtons can also display icons button = new JButton( ”text“ );
  • 20. Buttons 20 import javax.swing.*; public class SwingFrame { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); JButton button = new JButton( "Click Me!!" ); win.getContentPane().add( button ); win.setVisible(true); } } // SwingFrame
  • 21. Layout Manager 21 Layout Manager An interface that defines methods for positioning and sizing objects within a container. Java defines several default implementations of LayoutManager. Geometrical placement in a Container is controlled by a LayoutManager object
  • 22. Components, Containers, and Layout Managers 22 Containers may contain components (which means containers can contain containers!!). All containers come equipped with a layout manager which positions and shapes (lays out) the container's components. Much of the action in Swing occurs between components, containers, and their layout managers.
  • 23. Layout Managers 23 Layouts allow you to format components on the screen in a platform-independent way The standard JDK provides many classes that implement the LayoutManager interface, including: FlowLayout GridLayout BorderLayout BoxLayout
  • 24. Changing the Layout 24 1. To change the layout used in a container you first need to create the layout. 2. Then you invoke the setLayout() method on the container to use the new layout.  The layout manager should be established before any components are added to the container JPanel p = new JPanel() ; p.setLayout( new FlowLayout() );
  • 25. FlowLayout 25 FlowLayout is the default layout for the JPanel class. When you add components to the screen, they flow left to right (centered) based on the order added and the width of the screen. Very similar to word wrap and full justification on a word processor. If the screen is resized, the components' flow will change based on the new width and height
  • 26. Flow Layout 26 import javax.swing.*; import java.awt.*; public class ShowFlowLayout { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); win.getContentPane().setLayout( new FlowLayout() ); for ( int i = 0; i < 10; i++ ) { win.getContentPane().add( new JButton( String.valueOf( i ) ) ); } win.setVisible(true); } } // ShowFlowLayout
  • 28. GridLayout 28 Arranges components in rows and columns If the number of rows is specified columns = number of components / rows If the number of columns is specified Rows = number of components / columns The number of columns is ignored unless the number of rows is zero. The order in which you add components matters Component 1  (0,0), Component 2  (0,1), …... Components are resized to fit the row-column area
  • 29. Grid Layout 29 import javax.swing.*; import java.awt.*; public class ShowGridLayout { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); win.getContentPane().setLayout( new GridLayout( 2, 0 ) ); for ( int i = 0; i < 10; i++ ){ win.getContentPane().add( new JButton( String.valueOf( i ) ) ); } win.setVisible(true); } } // ShowGridLayout
  • 30. GridLayout 30 gridLayout( 2, 4 ) gridLayout( 0, 4 ) gridLayout( 4, 4 ) gridLayout( 10, 10 )
  • 31. BoxLayout 31 BoxLayout provides an easy way to lay out components horizontally or vertically. Components are added in order. BoxLayout attempts to arrange components at their preferred widths (for horizontal layout) or preferred heights (for vertical layout).
  • 32. BoxLayout example 32 import javax.swing.*; import java.awt.*; public class ShowBoxLayout { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); win.getContentPane().setLayout( new BoxLayout( win.getContentPane(), BoxLayout.X_AXIS ) ); for ( int i = 0; i < 10; i++ ){ win.getContentPane().add( new JButton( String.valueOf( i ) ) ); win.getContentPane().add( Box.createHorizontalGlue() ); } win.pack(); win.setVisible(true); } } // ShowBoxLayout
  • 33. BoxLayout 33 Note that components retain their preferred size.
  • 34. BorderLayout 34 BorderLayout provides 5 areas to hold components. These are named after the four different borders of the screen, North, South, East, West, and Center. When a Component is added to the layout, you must specify which area to place it in. The order in which components are added is not important. The center area will always be resized to be as large as possible
  • 35. BorderLayout 35 import javax.swing.*; import java.awt.*; public class ShowBorderLayout { public static void main( String args[] ) { JFrame win = new JFrame( "My First GUI Program" ); win.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); Container content = win.getContentPane(); content.setLayout( new BorderLayout() ); content.add( BorderLayout.NORTH, new JButton( "North" ) ); content.add( "South", new JButton( "South" ) ); content.add( "East", new JButton( "East" ) ); content.add( "West", new JButton( "West" ) ); content.add( "Center", new JButton( "Center" ) ); win.setVisible(true); } } // ShowBorderLayout
  • 37. Containers 37 A JFrame is not the only type of container that you can use in Swing The subclasses of Container are: JPanel JWindow JApplet Window is subclassed as follows: JDialog JFrame
  • 38. 38 Making components active Most components already appear to do something--buttons click, text appears To associate an action with a component, attach a listener to it Components send events, listeners listen for events Different components may send different events, and require different listeners
  • 39. 39 Listeners Listeners are interfaces, not classes class MyButtonListener implements ActionListener { An interface is a group of methods that must be supplied When you say implements, you are promising to supply those methods
  • 40. 40 Writing a Listener For a Button, you need an ActionListener b1.addActionListener (new MyButtonListener ( )); An ActionListener must have an actionPerformed(ActionEvent) method public void actionPerformed(ActionEvent e) { … }
  • 41. 41 MyButtonListener public void init () { ... b1.addActionListener (new MyButtonListener ()); } class MyButtonListener implements ActionListener { public void actionPerformed (ActionEvent e) { showStatus ("Ouch!"); } }
  • 42. 42 Listeners for TextFields An ActionListener listens for someone hitting the Enter key An ActionListener requires this method: public void actionPerformed (ActionEvent e) You can use getText( ) to get the text A TextListener listens for any and all keys A TextListener requires this method: public void textValueChanged(TextEvent e)
  • 43. 43 Summary I: Building a GUI Create a container, such as Frame or Applet Choose a layout manager Create more complex layouts by adding Panels; each Panel can have its own layout manager Create other components and add them to whichever Panels you like
  • 44. 44 Vocabulary AWT – The Abstract Window Toolkit provides basic graphics tools (tools for putting information on the screen) Swing – A much better set of graphics tools Container – a graphic element that can hold other graphic elements (and is itself a Component) Component – a graphic element (such as a Button or a TextArea) provided by a graphics toolkit listener – A piece of code that is activated when a particular kind of event occurs layout manager – An object whose job it is to arrange Components in a Container
  • 45. A Simple 4 Function Calculator 45
  • 47. CalcGui.java (pg. 1) 47 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CalcGui { // Labels for the buttons private static final String labels = "789X456/123-0C=+"; private static final int NUMROWS = 4; private static final int NUMCOLS = 4; private JLabel display; // The display public CalcGui( String name ) { // A Frame for the calculator JFrame win = new JFrame(name);
  • 48. CalcGui.java (pg. 2) 48 // Create the button panel JPanel buttons = new JPanel(); buttons.setLayout(new GridLayout(NUMROWS, NUMCOLS)); JButton b; for ( int i = 0 ; i < labels.length() ; i++ ) { b = new JButton( labels.substring( i, i + 1 ) ); buttons.add( b ); } // Create the display display = new JLabel( "0", JLabel.RIGHT ); display.setFont( new Font( "Courier", Font.BOLD, 24 ) );
  • 49. CalcGui.java (pg. 3) 49 // "Assemble" the calculator Container content = win.getContentPane(); content.setLayout( new BorderLayout() ); content.add( "North", display ); content.add( "Center", buttons ); // Display it and let the user run with it :-) win.pack(); win.setVisible(true); }