SlideShare une entreprise Scribd logo
1  sur  49
Agenda of today Presentation
 Introduction to GUI
 Introduction to AWT
 Introduction to Swing
 Difference b/w Swing and Awt
 Why we'll recomend to use "SWING"
 Introduction to Component,Container,Panels,window,Frame
 Implemention of JFrame and Adding component
 We can add component directly on frame
 Working with NETBEANS to make GUI
What is GUI( graphical user interface)?
 A GUI (pronounced “GOO-ee”) gives an application a
distinctive “look and feel.”
 A graphical user interface is a visual interface to a
program. GUIs are built from GUI components
(buttons,menus, labels etc). A GUI component is an
object with which the user interacts via the mouse or
keyboard.
 Together, the appearance and how user interacts with
the program are known as the program "look and feel".
 The classes that are used t o create GUI components
are part of the java.awt or javax.swin g package.
Both these packages provide rich set of user
interface components.
GUI vs Non-GUI
 The classes present in the awt and swing packages
can be classified into two broad categories. GUI
classes & Non-GUI Support classes.
 The GUI classes as the name indicates are visible
and user can interact with them. Examples of these
are JButton, JFrame & JRadioButton etc
 The Non-GUI support classes provide services and
perform necessary functions for GUI classes. They
do not produce any visual output. Examples of
these classes are Layout managers & Event
handling(will discussed latter by another group)
What is AWT?
 AWT stands for Abstract Windowing Toolkit contains original
but not pure GUI components that came with the first release
of JDK.
 These components are tied directly to the local platform‘s
(Windows, Linux, MAC etc)graphical user interface
capabilities. Thus results in a java program executing on
different java platforms(windows, Linux, Solaris etc) has a
different appearance and sometimes even different user
interaction on each platform.
 AWT components are often called Heavy Weight
Components (HWC) as they rely on the local platform‘s
windowing system.
 AWT component it creates a corresponding process on the
operating system.
 Inshort component of AWT are OS depended
About Swing
 These are the newest GUI components. Swing components
are written, manipulated and displayed completely in java,
therefore also called pure java components. The swing
component s allow the programmer to specify a
uniform look and feel across all platforms.
 javax.swing package is use to import
 not dedpend on operating system
 99% have lightweight components
 A rich set of class whic contain
 Jpanels,Jbutton,JTextarea,...............and so
 Name start from J of swing class
Superclasses of Swing’s Lightweight GUI Components
The Fig. shows an inheritance hierarchy of classes from which
lightweight Swing components inherit their common attributes and behaviors.
Swing vs AWT
 OS independent
 Light weight
 base on Write once use
anywhere
 feel and look
 rich set of object
 OS dedpendent
 Heavy weight
 Not consistent as
compared to Swing
 change behaviour due to
os
 less as compared to
swing
Visual diff.
Why we prefer to Swing
On the Basis of last slide that we disscused so we
can say that Swing is better becoz
not depend on OS
light weight
new version of JDK
write once use anywhere base
Component
 At the top of the AWT hierarchy is
theComponentclass.Componentis an abstract
class that
encapsulates all of the attributes of a visual
component. All user interface elements that are
displayed on the screen and that interact with the
user are subclasses ofComponent. It defines over
a hundred public methods that are responsible
for managing events, such as mouse and
keyboard input, positioning and sizing the
window, and repainting.
12
components examples
 JButton button = new JButton("Click me!");
 JLabel label = new JLabel("This is a JLabel");
 JTextField textField1 = new JTextField("This is the initial text");
 JTextField textField2 = new JTextField("Initial text", columns);
 JTextArea textArea1 = new JTextArea("Initial text");
 JTextArea textArea2 = new JTextArea(rows, columns);
 JTextArea textArea3 = new JTextArea("Initial text", rows, columns);
 JCheckBox checkbox = new JCheckBox("Label for checkbox");
 JRadioButton radioButton1 = new JRadioButton("Label for button");
 ButtonGroup group = new ButtonGroup();
group.add(radioButton1); group.add(radioButton2); etc.
 This is just a sampling of the available constructors; see the javax.swing API
for all the rest
Container
 TheContainerclass is a subclass ofComponent. It has
additional methods that allow other Componentobjects
to be nested within it. OtherContainerobjects can be
stored inside of a Container(since they are themselves
instances ofComponent). This makes for a multileveled
containment system. A container is responsible for
laying out (that is, positioning)
Two important methods the container class has add and setLayout.
Container are classified into two broad categories that are
Top Level containers andGeneral Purpose Containers Top
level containers can contain (add) other containers
as well as basic components (buttons, labels etc) while
general purpose containers are typically used to collect
basiccomponents and are added to top level containers.
Panel
 ThePanelclass is a concrete subclass ofContainer. It
doesn’t add any new methods; it simply implements
Container. A Panel may be thought of as a recursively
nestable, concrete screen component.
 When screen output is directed to an Frame/applet,it is
drawn on the surface of a Panel object.
 Panelis a window that does not contain a title bar, menu
bar, or border
Window
 TheWindowclass creates a top-level
window. A top-level window is not
contained within any other object; it sits
directly on the desktop. Generally, you
won’t createWindowobjects directly.
Instead, you will use a subclass of Window
called Frame, described next.
Frame
 Frame encapsulates what is commonly thought of as a
“window.” It is a subclass of Window and has a title bar,
menu bar, borders, and resizing corners.
 It contain Jlabel,textarea,button etc
 in previous hierarchy we observe that JFrame is a
frame is a window. So, it can be interpreted as
JFrame is a window.
 A simple frame
17
How to build a GUI
 Create a window in which to display things—usually a JFrame
(for an application), or a JApplet
 Use the setLayout(LayoutManager manager) method to
specify a layout manager
 Create some Components, such as buttons, panels, etc.
 Add your components to your display area, according to your
chosen layout manager
 Write some Listeners and attach them to your Components
 Interacting with a Component causes an Event to occur
 A Listener gets a message when an interesting event occurs, and executes
some code to deal with it
 Display your window
Step 1 and 2: Code for JFrame
import pakages
public class MyFirstFrame{
public static void main(String[] args) {
JFrame myFrame=new
JFrame("my frame");
myFrame.setSize(500, 500);//size
of the frame widht and height
myFrame.setVisible(true);
//this v.impt visibilty
myFrame.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
}
}
step#3: code for getting content area
JFrame myFrame=new JFrame("my frame");
myFrame.setSize(333, 333);
myFrame.setVisible(true);
myFrame.setDefaultCloseOperation(JFrame.
EXIT_ON_CLOSE);
 Container c =
myFrame.getContentPane(
);
 So now we are able to add component in
that area of frame
This content/panel area
step#4: code for Applaying layout
JFrame myFrame=new JFrame("title of frame");
myFrame.setSize(333, 333);
myFrame.setVisible(true);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = myFrame.getContent Pane();
c.setLayout( new FlowLayout());
 There are different method of layout but we will use one
for the code and introduce all in the next slide
 The purpose of layout that how they component are
apear in frame
Step 5: create & add components
JTextField t f = new
JTextField(10) ;
JButton b1 = new
JButton( "My Button");
JButton b2= new JButton("My
2nd Button");
Button b=new Button("Awt
button");
//Adding commponent to
container
c.add(tf);
c.add(b1);
Step 6: set size of frame and make it visible
myFrame.setDefaultCloseOperat
ion(JFrame.EXIT_ON_CLOS
E);
myFrame.setSize(200,150);
myFrame.setVisible(true);
output:
23
Add a layout manager
 The most important layout managers are:
 BorderLayout
 Provides five areas into which you can put components
 This is the default layout manager for both JFrame and JApplet
 FlowLayout
 Components are added left to right, top to bottom
 GridLayout
 Components are put in a rectangular grid
 All areas are the same size and shape
 BoxLayout
 Creates a horizontal row or a vertical stack
 This can be a little weird to use
24
BorderLayout
mport java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* @author Adil M
*/
public class JavaApplication9 {
///code for border layout
public static void main(String[] args) {
// TODO code application logic here
JFrame a=new JFrame("my frame");
a.setLayout(new BorderLayout());
JButton bt=new JButton("North");
a.add(bt,BorderLayout.NORTH);
JButton bt1=new JButton("west");
a.add(bt1,BorderLayout.WEST);
JButton bt2=new JButton("center");
a.add(bt2,BorderLayout.CENTER);
JButton bt3=new JButton("East");
a.add(bt3,BorderLayout.EAST);
JButton bt4=new JButton("south");
a.add(bt4,BorderLayout.SOUTH);
a.setSize(500,500);
a.setVisible(true);
a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
26
FlowLayout
 public class FlowLayoutExample extends JFrame {
public void init () {
setLayout(new FlowLayout ());
add(new JButton("One"));
add(new JButton("Two"));
add(new JButton("Three"));
add(new JButton("Four"));
add(new JButton("Five"));
add(new JButton("Six"));
}
}
27
GridLayout
 public class GridLayoutExample extends JApplet {
public void init() {
setLayout(new GridLayout(2, 4));
add(new JButton("One"));
add(new JButton("Two"));
add(new JButton("Three"));
add(new JButton("Four"));
add(new JButton("Five"));
}
}
28
BoxLayout
 public class BoxLayoutExample extends JApplet {
public void init () {
Box box = new Box(BoxLayout.Y_AXIS);
add(box);
box.add(new JButton("One"));
box.add(new JButton("Two"));
box.add(new JButton("Three"));
box.add(new JButton("Four"));
box.add(new JButton("Five"));
box.add(new JButton("Six"));
}
}
29
Nested layouts
 A JPanel is both a JContainer and a Component
 Because it’s a container, you can put other components into it
 Because it’s a component, you can put it into other containers
 All but the very simplest GUIs are built by creating
several JPanels, arranging them, and putting
components (possibly other JPanels) into them
 A good approach is to draw (on paper) the arrangement
you want, then finding an arrangement of JPanels and
their layout managers that accomplishes this
We can Add commponents on frame
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class JavaApplication9 {
public static void main(String[] args) {
JFrame a=new JFrame("my frame");
//SET LAYOUT FOR FRAME most imp
a.setLayout(new
FlowLayout());
JButton bt=new JButton("Button 1");
a.add(bt);
JButton bt1=new JButton("Button31");
a.add(bt1);
a.setSize(500,500);
a.setVisible(true);
a.setDefaultCloseOperation(JFrame.EXIT_ON_C
LOSE);
31
How to build a GUI(Step by Step)
Code for Simple GUI
// File GUITest.java
//Step 1: import packages
import java.awt .*;
import javax.swing.*;
public class GUITest {
JFrame myFrame ;
JTextField tf;
JButto n b;
//method used for set ting layout of GUI
public void initGUI ( ) {
//St ep 2: setup the top level cont ainer
myFrame = new JFrame();
continue......
//St ep 3: Get the component area of top-level container
Container c = myFrame.getContent Pane();
//Step 4: Apply layo ut s
c.setLayout( new FlowLayout( ) );
//Step 5: create & add components
JTextField t f = new JTextField(10) ;
JButton b1 = new JButton( "My Button");
c.add(tf);
c.add(b1);
//Step 6: set size of frame and make it visible
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(200,150);
myFrame.setVisible(true);
} //end initGUI method
continue......
public GUITest ( ) { // default constructor
initGUI ();
}
public static void main (Strin g args[ ]) {
GUITest gui = new GUITest();
}
}
Code for simple layout of calculator
To make the calculator GUI shown
above, take JFrame (top level
container) and set it s layout to
border. Than take JPanel (general
purpose container) and set its layout
to Grid with 4 rows and 4 columns.
calculator cont......
public class NewClass {
JFrame fCalc=new JFrame("Swing Presentation by Adil");
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b0;
JButton bPlus,bMinus,bMul,bPoint,bEqual,bCl ,ear;
JPanel pButtons;
JTextField tfAn, swer;
JLabel lMyCalc;
public static void main(String[] args)
{
NewClass v= new NewClass();
}
public void method(){
try
{
bPlus=new JButton("");
b1=new JButton("1");
b2=new JButton("2");
b3=new JButton("3");
b4=new JButton("4");
b5=new JButton("5");
b6=new JButton("6");
b7=new JButton("7");
b8=new JButton("8");
b9=new JButton("9");
b0=new JButton("0");
calculator cont......
bMinus = new JButton("-");
bMul = new JButton("*");
bPoint = new JButton(".");
bEqual = new JButton("=");
bCl = new JButton("C");
tfAn = new JTextField(10);
tfAn.setSize(20, 20);
lMyCalc = new JLabel("My Clacualator");
//creating panel object and setting its layout
pButtons = new JPanel (new GridLayout(4,4));
//adding components (buttons) to panel
pButtons.add(b1);
pButtons.add(b2);
pButtons.add(b3);
pButtons.add(bCl);
pButtons.add(b4);
pButtons.add(b5);
pButtons.add(b6);
pButtons.add(bMul);
pButtons.add(b7);
pButtons.add(b8);
pButtons.add(b9);
pButtons.add(bMinus);
pButtons.add(b0);
pButtons.add(bPoint);
pButtons.add(bPlus);
pButtons.add(bEqual);
// getting componenet area of JFrame
Container con=new Container();
con=fCalc.getContentPane();
con.setLayout(new BorderLayout()) ;
//adding components to container
con.add(tfAn, BorderLayout.NORTH);
con.add(lMyCalc, BorderLayout.SOUTH);
con.add(pButtons, BorderLayout.CENTER);
fCalc.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
fCalc.setSize(300, 300);
fCalc.setVisible(true);
}
calculator cont......
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.getStackTrace());
}
}
public NewClass ()
{ // default const ructor
method();
}
}
out put
40
Getting values
 Some user actions normally cause the program to do
something: clicking a button, or selecting from a menu
 Some user actions set values to be used later: entering
text, setting a checkbox or a radio button
 You can listen for events from these, but it’s not usually a
good idea
 Instead, read their values when you need them
 String myText = myJTextField.getText();
 String myText = myJTextArea.getText();
 boolean checked = myJCheckBox.isSelected();
 boolean selected1 = myJRadioButton1.isSelected();
41
Enabling and disabling components
 It is poor style to remove components you don’t want
the user to be able to use
 “Where did it go? It was here a minute ago!”
 It’s better to enable and disable controls
 Disabled controls appear “grayed out”
 The user may wonder why?, but it’s still less confusing
 anyComponent.setEnabled(enabled);
 Parameter should be true to enable, false to disable
42
Dialogs
 A dialog (small accessory window) can be modal or
nonmodal
 When your code opens a modal dialog, it waits for a result
from the dialog before continuing
 When your code opens a nonmodal dialog, it does so in a
separate thread, and your code just keeps going
 Sun supplies a few simple (but useful) modal dialogs for
your use
 You can create your own dialogs (with JDialog), but
they are nonmodal by default
43
Message dialogs
 JOptionPane.showMessageDialog(parentJFrame,
"This is a JOptionPane "message" dialog.");
 Notice that showMessageDialog is a static method of
JOptionPane
 The “parentJFrame” is typically your main GUI
window (but it’s OK to use null if you don’t have a
main GUI window)
44
Confirm dialogs
 int yesNo =
JOptionPane.showConfirmDialog(parentJFrame,
"Is this what you wanted to see?");
 if (yesNo == JOptionPane.YES_OPTION) { ... }
45
Input dialogs
 String userName =
JOptionPane.showInputDialog(parentJFrame,
"What is your name?")
46
Option dialogs
 Object[] options =
new String[] {"English", "Chinese", "French", "German" };
int option =
JOptionPane.showOptionDialog(parentJFrame,
"Choose an option:",
"Option Dialog",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]); // use as default
 Fourth argument could be JOptionPane.YES_NO_CANCEL_OPTION
 Fifth argument specifies which icon to use in the dialog; it could be one of
ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, or
PLAIN_MESSAGE
 Sixth argument (null above) can specify a custom icon
47
Load file dialogs
 JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Load which file?");
 int result = chooser.showOpenDialog(enclosingJFrame);
if (result == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
// use file
}
 You could also test for
CANCEL_OPTION or
ERROR_OPTION
 You will get back a File
object; to use it, you must
know how to do file I/O
48
Save file dialogs
 JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle(“Save file as?");
 int result = chooser.showSaveDialog(enclosingJFrame);
if (result == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
// use file
}
 You could also test for
CANCEL_OPTION or
ERROR_OPTION
 You will get back a File
object; to use it, you must
know how to do file I/O
Review
 Introduction to GUI
 Introduction to AWT
 Introduction to Swing
 Difference b/w Swing and Awt
 Why we'll recomend to use "SWING"
 Introduction to Component,Container,Panels,window,Frame
 Implemention of JFrame and Adding component
 Working with NETBEANS to make GUI

Contenu connexe

Tendances

Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in javaHitesh Kumar
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp PresentationVishwa Mohan
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For SyntaxPravinYalameli
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - ObjectsWebStackAcademy
 
Java Presentation
Java PresentationJava Presentation
Java Presentationpm2214
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)slire
 

Tendances (20)

Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
CSharp Presentation
CSharp PresentationCSharp Presentation
CSharp Presentation
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
VB net lab.pdf
VB net lab.pdfVB net lab.pdf
VB net lab.pdf
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Java swing
Java swingJava swing
Java swing
 
Java 8 date & time api
Java 8 date & time apiJava 8 date & time api
Java 8 date & time api
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Java program structure
Java program structureJava program structure
Java program structure
 

Similaire à Swing and AWT in java

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
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Javasuraj pandey
 
Computer Programming NC III - Java Swing.pptx
Computer Programming NC III - Java Swing.pptxComputer Programming NC III - Java Swing.pptx
Computer Programming NC III - Java Swing.pptxjonathancapitulo2
 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window ToolkitRutvaThakkar1
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01Ankit Dubey
 
SWING USING JAVA WITH VARIOUS COMPONENTS
SWING USING  JAVA WITH VARIOUS COMPONENTSSWING USING  JAVA WITH VARIOUS COMPONENTS
SWING USING JAVA WITH VARIOUS COMPONENTSbharathiv53
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptsharanyak0721
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01JONDHLEPOLY
 
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
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1PRN USM
 
Advanced java lab swing mvc awt
Advanced java lab swing mvc awtAdvanced java lab swing mvc awt
Advanced java lab swing mvc awtvishal choudhary
 
Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1Muhammad Shebl Farag
 

Similaire à Swing and AWT in java (20)

Chap1 1 1
Chap1 1 1Chap1 1 1
Chap1 1 1
 
Chap1 1.1
Chap1 1.1Chap1 1.1
Chap1 1.1
 
Z blue introduction to gui (39023299)
Z blue   introduction to gui (39023299)Z blue   introduction to gui (39023299)
Z blue introduction to gui (39023299)
 
Ingles 2do parcial
Ingles   2do parcialIngles   2do parcial
Ingles 2do parcial
 
Basic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in JavaBasic of Abstract Window Toolkit(AWT) in Java
Basic of Abstract Window Toolkit(AWT) in Java
 
Computer Programming NC III - Java Swing.pptx
Computer Programming NC III - Java Swing.pptxComputer Programming NC III - Java Swing.pptx
Computer Programming NC III - Java Swing.pptx
 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window Toolkit
 
GUI.pdf
GUI.pdfGUI.pdf
GUI.pdf
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
 
SWING USING JAVA WITH VARIOUS COMPONENTS
SWING USING  JAVA WITH VARIOUS COMPONENTSSWING USING  JAVA WITH VARIOUS COMPONENTS
SWING USING JAVA WITH VARIOUS COMPONENTS
 
L11cs2110sp13
L11cs2110sp13L11cs2110sp13
L11cs2110sp13
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
 
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
 
14a-gui.ppt
14a-gui.ppt14a-gui.ppt
14a-gui.ppt
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
Advanced java lab swing mvc awt
Advanced java lab swing mvc awtAdvanced java lab swing mvc awt
Advanced java lab swing mvc awt
 
Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1
 
Awt and swing in java
Awt and swing in javaAwt and swing in java
Awt and swing in java
 
GUI components in Java
GUI components in JavaGUI components in Java
GUI components in Java
 

Plus de Adil Mehmoood

Docker + Node "hello world" Application
Docker + Node "hello world" ApplicationDocker + Node "hello world" Application
Docker + Node "hello world" ApplicationAdil Mehmoood
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQLAdil Mehmoood
 
What is feasibility study and what is contracts and its type
What is feasibility study and what is contracts and its typeWhat is feasibility study and what is contracts and its type
What is feasibility study and what is contracts and its typeAdil Mehmoood
 
Inner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in javaInner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in javaAdil Mehmoood
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAdil Mehmoood
 
Project Engineer and Deputy project manger
Project Engineer and Deputy project manger Project Engineer and Deputy project manger
Project Engineer and Deputy project manger Adil Mehmoood
 
Software Engineering 2 lecture slide
Software Engineering 2 lecture slideSoftware Engineering 2 lecture slide
Software Engineering 2 lecture slideAdil Mehmoood
 
Sliding window and error control
Sliding window and error controlSliding window and error control
Sliding window and error controlAdil Mehmoood
 
Proposal defence format
Proposal defence formatProposal defence format
Proposal defence formatAdil Mehmoood
 
Shading and two type of shading flat shading and gauraud shading with coding ...
Shading and two type of shading flat shading and gauraud shading with coding ...Shading and two type of shading flat shading and gauraud shading with coding ...
Shading and two type of shading flat shading and gauraud shading with coding ...Adil Mehmoood
 
System quality attributes
System quality attributes System quality attributes
System quality attributes Adil Mehmoood
 
Graph Clustering and cluster
Graph Clustering and clusterGraph Clustering and cluster
Graph Clustering and clusterAdil Mehmoood
 
diseases caused by computer
diseases caused by computerdiseases caused by computer
diseases caused by computerAdil Mehmoood
 
Diseases caused by Computer
Diseases caused by ComputerDiseases caused by Computer
Diseases caused by ComputerAdil Mehmoood
 
What is Resume ,purpose and objective of resume and type of resume
What is Resume ,purpose and objective of resume and type of resumeWhat is Resume ,purpose and objective of resume and type of resume
What is Resume ,purpose and objective of resume and type of resumeAdil Mehmoood
 
Multiplexing and switching(TDM ,FDM, Data gram, circuit switching)
Multiplexing and switching(TDM ,FDM, Data gram, circuit switching)Multiplexing and switching(TDM ,FDM, Data gram, circuit switching)
Multiplexing and switching(TDM ,FDM, Data gram, circuit switching)Adil Mehmoood
 

Plus de Adil Mehmoood (19)

Docker + Node "hello world" Application
Docker + Node "hello world" ApplicationDocker + Node "hello world" Application
Docker + Node "hello world" Application
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
 
What is feasibility study and what is contracts and its type
What is feasibility study and what is contracts and its typeWhat is feasibility study and what is contracts and its type
What is feasibility study and what is contracts and its type
 
Inner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in javaInner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Project Engineer and Deputy project manger
Project Engineer and Deputy project manger Project Engineer and Deputy project manger
Project Engineer and Deputy project manger
 
Software Engineering 2 lecture slide
Software Engineering 2 lecture slideSoftware Engineering 2 lecture slide
Software Engineering 2 lecture slide
 
Expert system
Expert systemExpert system
Expert system
 
Sliding window and error control
Sliding window and error controlSliding window and error control
Sliding window and error control
 
Proposal defence format
Proposal defence formatProposal defence format
Proposal defence format
 
Shading and two type of shading flat shading and gauraud shading with coding ...
Shading and two type of shading flat shading and gauraud shading with coding ...Shading and two type of shading flat shading and gauraud shading with coding ...
Shading and two type of shading flat shading and gauraud shading with coding ...
 
Computer vesion
Computer vesionComputer vesion
Computer vesion
 
System quality attributes
System quality attributes System quality attributes
System quality attributes
 
Graph Clustering and cluster
Graph Clustering and clusterGraph Clustering and cluster
Graph Clustering and cluster
 
Token ring 802.5
Token ring 802.5Token ring 802.5
Token ring 802.5
 
diseases caused by computer
diseases caused by computerdiseases caused by computer
diseases caused by computer
 
Diseases caused by Computer
Diseases caused by ComputerDiseases caused by Computer
Diseases caused by Computer
 
What is Resume ,purpose and objective of resume and type of resume
What is Resume ,purpose and objective of resume and type of resumeWhat is Resume ,purpose and objective of resume and type of resume
What is Resume ,purpose and objective of resume and type of resume
 
Multiplexing and switching(TDM ,FDM, Data gram, circuit switching)
Multiplexing and switching(TDM ,FDM, Data gram, circuit switching)Multiplexing and switching(TDM ,FDM, Data gram, circuit switching)
Multiplexing and switching(TDM ,FDM, Data gram, circuit switching)
 

Dernier

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 

Dernier (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 

Swing and AWT in java

  • 1.
  • 2. Agenda of today Presentation  Introduction to GUI  Introduction to AWT  Introduction to Swing  Difference b/w Swing and Awt  Why we'll recomend to use "SWING"  Introduction to Component,Container,Panels,window,Frame  Implemention of JFrame and Adding component  We can add component directly on frame  Working with NETBEANS to make GUI
  • 3. What is GUI( graphical user interface)?  A GUI (pronounced “GOO-ee”) gives an application a distinctive “look and feel.”  A graphical user interface is a visual interface to a program. GUIs are built from GUI components (buttons,menus, labels etc). A GUI component is an object with which the user interacts via the mouse or keyboard.  Together, the appearance and how user interacts with the program are known as the program "look and feel".  The classes that are used t o create GUI components are part of the java.awt or javax.swin g package. Both these packages provide rich set of user interface components.
  • 4. GUI vs Non-GUI  The classes present in the awt and swing packages can be classified into two broad categories. GUI classes & Non-GUI Support classes.  The GUI classes as the name indicates are visible and user can interact with them. Examples of these are JButton, JFrame & JRadioButton etc  The Non-GUI support classes provide services and perform necessary functions for GUI classes. They do not produce any visual output. Examples of these classes are Layout managers & Event handling(will discussed latter by another group)
  • 5. What is AWT?  AWT stands for Abstract Windowing Toolkit contains original but not pure GUI components that came with the first release of JDK.  These components are tied directly to the local platform‘s (Windows, Linux, MAC etc)graphical user interface capabilities. Thus results in a java program executing on different java platforms(windows, Linux, Solaris etc) has a different appearance and sometimes even different user interaction on each platform.  AWT components are often called Heavy Weight Components (HWC) as they rely on the local platform‘s windowing system.  AWT component it creates a corresponding process on the operating system.  Inshort component of AWT are OS depended
  • 6. About Swing  These are the newest GUI components. Swing components are written, manipulated and displayed completely in java, therefore also called pure java components. The swing component s allow the programmer to specify a uniform look and feel across all platforms.  javax.swing package is use to import  not dedpend on operating system  99% have lightweight components  A rich set of class whic contain  Jpanels,Jbutton,JTextarea,...............and so  Name start from J of swing class
  • 7. Superclasses of Swing’s Lightweight GUI Components The Fig. shows an inheritance hierarchy of classes from which lightweight Swing components inherit their common attributes and behaviors.
  • 8. Swing vs AWT  OS independent  Light weight  base on Write once use anywhere  feel and look  rich set of object  OS dedpendent  Heavy weight  Not consistent as compared to Swing  change behaviour due to os  less as compared to swing
  • 10. Why we prefer to Swing On the Basis of last slide that we disscused so we can say that Swing is better becoz not depend on OS light weight new version of JDK write once use anywhere base
  • 11. Component  At the top of the AWT hierarchy is theComponentclass.Componentis an abstract class that encapsulates all of the attributes of a visual component. All user interface elements that are displayed on the screen and that interact with the user are subclasses ofComponent. It defines over a hundred public methods that are responsible for managing events, such as mouse and keyboard input, positioning and sizing the window, and repainting.
  • 12. 12 components examples  JButton button = new JButton("Click me!");  JLabel label = new JLabel("This is a JLabel");  JTextField textField1 = new JTextField("This is the initial text");  JTextField textField2 = new JTextField("Initial text", columns);  JTextArea textArea1 = new JTextArea("Initial text");  JTextArea textArea2 = new JTextArea(rows, columns);  JTextArea textArea3 = new JTextArea("Initial text", rows, columns);  JCheckBox checkbox = new JCheckBox("Label for checkbox");  JRadioButton radioButton1 = new JRadioButton("Label for button");  ButtonGroup group = new ButtonGroup(); group.add(radioButton1); group.add(radioButton2); etc.  This is just a sampling of the available constructors; see the javax.swing API for all the rest
  • 13. Container  TheContainerclass is a subclass ofComponent. It has additional methods that allow other Componentobjects to be nested within it. OtherContainerobjects can be stored inside of a Container(since they are themselves instances ofComponent). This makes for a multileveled containment system. A container is responsible for laying out (that is, positioning) Two important methods the container class has add and setLayout. Container are classified into two broad categories that are Top Level containers andGeneral Purpose Containers Top level containers can contain (add) other containers as well as basic components (buttons, labels etc) while general purpose containers are typically used to collect basiccomponents and are added to top level containers.
  • 14. Panel  ThePanelclass is a concrete subclass ofContainer. It doesn’t add any new methods; it simply implements Container. A Panel may be thought of as a recursively nestable, concrete screen component.  When screen output is directed to an Frame/applet,it is drawn on the surface of a Panel object.  Panelis a window that does not contain a title bar, menu bar, or border
  • 15. Window  TheWindowclass creates a top-level window. A top-level window is not contained within any other object; it sits directly on the desktop. Generally, you won’t createWindowobjects directly. Instead, you will use a subclass of Window called Frame, described next.
  • 16. Frame  Frame encapsulates what is commonly thought of as a “window.” It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners.  It contain Jlabel,textarea,button etc  in previous hierarchy we observe that JFrame is a frame is a window. So, it can be interpreted as JFrame is a window.  A simple frame
  • 17. 17 How to build a GUI  Create a window in which to display things—usually a JFrame (for an application), or a JApplet  Use the setLayout(LayoutManager manager) method to specify a layout manager  Create some Components, such as buttons, panels, etc.  Add your components to your display area, according to your chosen layout manager  Write some Listeners and attach them to your Components  Interacting with a Component causes an Event to occur  A Listener gets a message when an interesting event occurs, and executes some code to deal with it  Display your window
  • 18. Step 1 and 2: Code for JFrame import pakages public class MyFirstFrame{ public static void main(String[] args) { JFrame myFrame=new JFrame("my frame"); myFrame.setSize(500, 500);//size of the frame widht and height myFrame.setVisible(true); //this v.impt visibilty myFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); } }
  • 19. step#3: code for getting content area JFrame myFrame=new JFrame("my frame"); myFrame.setSize(333, 333); myFrame.setVisible(true); myFrame.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE);  Container c = myFrame.getContentPane( );  So now we are able to add component in that area of frame This content/panel area
  • 20. step#4: code for Applaying layout JFrame myFrame=new JFrame("title of frame"); myFrame.setSize(333, 333); myFrame.setVisible(true); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container c = myFrame.getContent Pane(); c.setLayout( new FlowLayout());  There are different method of layout but we will use one for the code and introduce all in the next slide  The purpose of layout that how they component are apear in frame
  • 21. Step 5: create & add components JTextField t f = new JTextField(10) ; JButton b1 = new JButton( "My Button"); JButton b2= new JButton("My 2nd Button"); Button b=new Button("Awt button"); //Adding commponent to container c.add(tf); c.add(b1);
  • 22. Step 6: set size of frame and make it visible myFrame.setDefaultCloseOperat ion(JFrame.EXIT_ON_CLOS E); myFrame.setSize(200,150); myFrame.setVisible(true); output:
  • 23. 23 Add a layout manager  The most important layout managers are:  BorderLayout  Provides five areas into which you can put components  This is the default layout manager for both JFrame and JApplet  FlowLayout  Components are added left to right, top to bottom  GridLayout  Components are put in a rectangular grid  All areas are the same size and shape  BoxLayout  Creates a horizontal row or a vertical stack  This can be a little weird to use
  • 25. mport java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; /** * @author Adil M */ public class JavaApplication9 { ///code for border layout public static void main(String[] args) { // TODO code application logic here JFrame a=new JFrame("my frame"); a.setLayout(new BorderLayout()); JButton bt=new JButton("North"); a.add(bt,BorderLayout.NORTH); JButton bt1=new JButton("west"); a.add(bt1,BorderLayout.WEST); JButton bt2=new JButton("center"); a.add(bt2,BorderLayout.CENTER); JButton bt3=new JButton("East"); a.add(bt3,BorderLayout.EAST); JButton bt4=new JButton("south"); a.add(bt4,BorderLayout.SOUTH); a.setSize(500,500); a.setVisible(true); a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
  • 26. 26 FlowLayout  public class FlowLayoutExample extends JFrame { public void init () { setLayout(new FlowLayout ()); add(new JButton("One")); add(new JButton("Two")); add(new JButton("Three")); add(new JButton("Four")); add(new JButton("Five")); add(new JButton("Six")); } }
  • 27. 27 GridLayout  public class GridLayoutExample extends JApplet { public void init() { setLayout(new GridLayout(2, 4)); add(new JButton("One")); add(new JButton("Two")); add(new JButton("Three")); add(new JButton("Four")); add(new JButton("Five")); } }
  • 28. 28 BoxLayout  public class BoxLayoutExample extends JApplet { public void init () { Box box = new Box(BoxLayout.Y_AXIS); add(box); box.add(new JButton("One")); box.add(new JButton("Two")); box.add(new JButton("Three")); box.add(new JButton("Four")); box.add(new JButton("Five")); box.add(new JButton("Six")); } }
  • 29. 29 Nested layouts  A JPanel is both a JContainer and a Component  Because it’s a container, you can put other components into it  Because it’s a component, you can put it into other containers  All but the very simplest GUIs are built by creating several JPanels, arranging them, and putting components (possibly other JPanels) into them  A good approach is to draw (on paper) the arrangement you want, then finding an arrangement of JPanels and their layout managers that accomplishes this
  • 30. We can Add commponents on frame import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; public class JavaApplication9 { public static void main(String[] args) { JFrame a=new JFrame("my frame"); //SET LAYOUT FOR FRAME most imp a.setLayout(new FlowLayout()); JButton bt=new JButton("Button 1"); a.add(bt); JButton bt1=new JButton("Button31"); a.add(bt1); a.setSize(500,500); a.setVisible(true); a.setDefaultCloseOperation(JFrame.EXIT_ON_C LOSE);
  • 31. 31 How to build a GUI(Step by Step) Code for Simple GUI // File GUITest.java //Step 1: import packages import java.awt .*; import javax.swing.*; public class GUITest { JFrame myFrame ; JTextField tf; JButto n b; //method used for set ting layout of GUI public void initGUI ( ) { //St ep 2: setup the top level cont ainer myFrame = new JFrame();
  • 32. continue...... //St ep 3: Get the component area of top-level container Container c = myFrame.getContent Pane(); //Step 4: Apply layo ut s c.setLayout( new FlowLayout( ) ); //Step 5: create & add components JTextField t f = new JTextField(10) ; JButton b1 = new JButton( "My Button"); c.add(tf); c.add(b1); //Step 6: set size of frame and make it visible myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setSize(200,150); myFrame.setVisible(true); } //end initGUI method
  • 33. continue...... public GUITest ( ) { // default constructor initGUI (); } public static void main (Strin g args[ ]) { GUITest gui = new GUITest(); } }
  • 34. Code for simple layout of calculator To make the calculator GUI shown above, take JFrame (top level container) and set it s layout to border. Than take JPanel (general purpose container) and set its layout to Grid with 4 rows and 4 columns.
  • 35. calculator cont...... public class NewClass { JFrame fCalc=new JFrame("Swing Presentation by Adil"); JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b0; JButton bPlus,bMinus,bMul,bPoint,bEqual,bCl ,ear; JPanel pButtons; JTextField tfAn, swer; JLabel lMyCalc; public static void main(String[] args) { NewClass v= new NewClass(); } public void method(){ try { bPlus=new JButton(""); b1=new JButton("1"); b2=new JButton("2"); b3=new JButton("3"); b4=new JButton("4"); b5=new JButton("5"); b6=new JButton("6"); b7=new JButton("7"); b8=new JButton("8"); b9=new JButton("9"); b0=new JButton("0");
  • 36. calculator cont...... bMinus = new JButton("-"); bMul = new JButton("*"); bPoint = new JButton("."); bEqual = new JButton("="); bCl = new JButton("C"); tfAn = new JTextField(10); tfAn.setSize(20, 20); lMyCalc = new JLabel("My Clacualator"); //creating panel object and setting its layout pButtons = new JPanel (new GridLayout(4,4)); //adding components (buttons) to panel pButtons.add(b1); pButtons.add(b2); pButtons.add(b3); pButtons.add(bCl);
  • 37. pButtons.add(b4); pButtons.add(b5); pButtons.add(b6); pButtons.add(bMul); pButtons.add(b7); pButtons.add(b8); pButtons.add(b9); pButtons.add(bMinus); pButtons.add(b0); pButtons.add(bPoint); pButtons.add(bPlus); pButtons.add(bEqual); // getting componenet area of JFrame Container con=new Container(); con=fCalc.getContentPane(); con.setLayout(new BorderLayout()) ; //adding components to container con.add(tfAn, BorderLayout.NORTH); con.add(lMyCalc, BorderLayout.SOUTH); con.add(pButtons, BorderLayout.CENTER); fCalc.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); fCalc.setSize(300, 300); fCalc.setVisible(true); } calculator cont......
  • 40. 40 Getting values  Some user actions normally cause the program to do something: clicking a button, or selecting from a menu  Some user actions set values to be used later: entering text, setting a checkbox or a radio button  You can listen for events from these, but it’s not usually a good idea  Instead, read their values when you need them  String myText = myJTextField.getText();  String myText = myJTextArea.getText();  boolean checked = myJCheckBox.isSelected();  boolean selected1 = myJRadioButton1.isSelected();
  • 41. 41 Enabling and disabling components  It is poor style to remove components you don’t want the user to be able to use  “Where did it go? It was here a minute ago!”  It’s better to enable and disable controls  Disabled controls appear “grayed out”  The user may wonder why?, but it’s still less confusing  anyComponent.setEnabled(enabled);  Parameter should be true to enable, false to disable
  • 42. 42 Dialogs  A dialog (small accessory window) can be modal or nonmodal  When your code opens a modal dialog, it waits for a result from the dialog before continuing  When your code opens a nonmodal dialog, it does so in a separate thread, and your code just keeps going  Sun supplies a few simple (but useful) modal dialogs for your use  You can create your own dialogs (with JDialog), but they are nonmodal by default
  • 43. 43 Message dialogs  JOptionPane.showMessageDialog(parentJFrame, "This is a JOptionPane "message" dialog.");  Notice that showMessageDialog is a static method of JOptionPane  The “parentJFrame” is typically your main GUI window (but it’s OK to use null if you don’t have a main GUI window)
  • 44. 44 Confirm dialogs  int yesNo = JOptionPane.showConfirmDialog(parentJFrame, "Is this what you wanted to see?");  if (yesNo == JOptionPane.YES_OPTION) { ... }
  • 45. 45 Input dialogs  String userName = JOptionPane.showInputDialog(parentJFrame, "What is your name?")
  • 46. 46 Option dialogs  Object[] options = new String[] {"English", "Chinese", "French", "German" }; int option = JOptionPane.showOptionDialog(parentJFrame, "Choose an option:", "Option Dialog", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); // use as default  Fourth argument could be JOptionPane.YES_NO_CANCEL_OPTION  Fifth argument specifies which icon to use in the dialog; it could be one of ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, or PLAIN_MESSAGE  Sixth argument (null above) can specify a custom icon
  • 47. 47 Load file dialogs  JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Load which file?");  int result = chooser.showOpenDialog(enclosingJFrame); if (result == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); // use file }  You could also test for CANCEL_OPTION or ERROR_OPTION  You will get back a File object; to use it, you must know how to do file I/O
  • 48. 48 Save file dialogs  JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(“Save file as?");  int result = chooser.showSaveDialog(enclosingJFrame); if (result == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); // use file }  You could also test for CANCEL_OPTION or ERROR_OPTION  You will get back a File object; to use it, you must know how to do file I/O
  • 49. Review  Introduction to GUI  Introduction to AWT  Introduction to Swing  Difference b/w Swing and Awt  Why we'll recomend to use "SWING"  Introduction to Component,Container,Panels,window,Frame  Implemention of JFrame and Adding component  Working with NETBEANS to make GUI