SlideShare a Scribd company logo
Swing and AWT in java
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
Ad

More Related Content

What's hot (20)

Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
vishal choudhary
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
VINOTH R
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
Jussi Pohjolainen
 
Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 
Java awt
Java awtJava awt
Java awt
Arati Gadgil
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Lovely Professional University
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
shanmuga rajan
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
Madishetty Prathibha
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 

Similar to Swing and AWT in java (20)

java swing notes in easy manner for UG students
java swing notes in easy manner for UG studentsjava swing notes in easy manner for UG students
java swing notes in easy manner for UG students
RameshPrasadBhatta2
 
Chap1 1 1
Chap1 1 1Chap1 1 1
Chap1 1 1
Hemo Chella
 
Chap1 1.1
Chap1 1.1Chap1 1.1
Chap1 1.1
Hemo Chella
 
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
 
Ingles 2do parcial
Ingles   2do parcialIngles   2do parcial
Ingles 2do parcial
Harry Ostaiza
 
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
suraj pandey
 
Java swing
Java swingJava swing
Java swing
ssuser3a47cb
 
Creating GUI.pptx Gui graphical user interface
Creating GUI.pptx Gui graphical user interfaceCreating GUI.pptx Gui graphical user interface
Creating GUI.pptx Gui graphical user interface
pikachu02434
 
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
jonathancapitulo2
 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window Toolkit
RutvaThakkar1
 
GUI.pdf
GUI.pdfGUI.pdf
GUI.pdf
AbuSufyan82
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
Ankit Dubey
 
SWING USING JAVA WITH VARIOUS COMPONENTS
SWING USING  JAVA WITH VARIOUS COMPONENTSSWING USING  JAVA WITH VARIOUS COMPONENTS
SWING USING JAVA WITH VARIOUS COMPONENTS
bharathiv53
 
L11cs2110sp13
L11cs2110sp13L11cs2110sp13
L11cs2110sp13
karan saini
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
sharanyak0721
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
JONDHLEPOLY
 
Java_Unit6pptx__2024_04_13_18_18_07.pptx
Java_Unit6pptx__2024_04_13_18_18_07.pptxJava_Unit6pptx__2024_04_13_18_18_07.pptx
Java_Unit6pptx__2024_04_13_18_18_07.pptx
lakhatariyajaimin09
 
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
MohanYedatkar
 
14a-gui.ppt
14a-gui.ppt14a-gui.ppt
14a-gui.ppt
DrDGayathriDevi
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
PRN USM
 
java swing notes in easy manner for UG students
java swing notes in easy manner for UG studentsjava swing notes in easy manner for UG students
java swing notes in easy manner for UG students
RameshPrasadBhatta2
 
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 Java
suraj pandey
 
Creating GUI.pptx Gui graphical user interface
Creating GUI.pptx Gui graphical user interfaceCreating GUI.pptx Gui graphical user interface
Creating GUI.pptx Gui graphical user interface
pikachu02434
 
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
jonathancapitulo2
 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window Toolkit
RutvaThakkar1
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
Ankit Dubey
 
SWING USING JAVA WITH VARIOUS COMPONENTS
SWING USING  JAVA WITH VARIOUS COMPONENTSSWING USING  JAVA WITH VARIOUS COMPONENTS
SWING USING JAVA WITH VARIOUS COMPONENTS
bharathiv53
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
sharanyak0721
 
Ajp notes-chapter-01
Ajp notes-chapter-01Ajp notes-chapter-01
Ajp notes-chapter-01
JONDHLEPOLY
 
Java_Unit6pptx__2024_04_13_18_18_07.pptx
Java_Unit6pptx__2024_04_13_18_18_07.pptxJava_Unit6pptx__2024_04_13_18_18_07.pptx
Java_Unit6pptx__2024_04_13_18_18_07.pptx
lakhatariyajaimin09
 
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
MohanYedatkar
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
PRN USM
 
Ad

More from Adil Mehmoood (19)

Docker + Node "hello world" Application
Docker + Node "hello world" ApplicationDocker + Node "hello world" Application
Docker + Node "hello world" Application
Adil Mehmoood
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
Adil 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 type
Adil 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 java
Adil Mehmoood
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Adil 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 slide
Adil Mehmoood
 
Expert system
Expert systemExpert system
Expert system
Adil Mehmoood
 
Sliding window and error control
Sliding window and error controlSliding window and error control
Sliding window and error control
Adil Mehmoood
 
Proposal defence format
Proposal defence formatProposal defence format
Proposal defence format
Adil 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
 
Computer vesion
Computer vesionComputer vesion
Computer vesion
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 cluster
Adil Mehmoood
 
Token ring 802.5
Token ring 802.5Token ring 802.5
Token ring 802.5
Adil Mehmoood
 
diseases caused by computer
diseases caused by computerdiseases caused by computer
diseases caused by computer
Adil Mehmoood
 
Diseases caused by Computer
Diseases caused by ComputerDiseases caused by Computer
Diseases caused by Computer
Adil 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 resume
Adil 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
 
Docker + Node "hello world" Application
Docker + Node "hello world" ApplicationDocker + Node "hello world" Application
Docker + Node "hello world" Application
Adil Mehmoood
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
Adil 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 type
Adil 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 java
Adil Mehmoood
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Adil 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 slide
Adil Mehmoood
 
Sliding window and error control
Sliding window and error controlSliding window and error control
Sliding window and error control
Adil Mehmoood
 
Proposal defence format
Proposal defence formatProposal defence format
Proposal defence format
Adil 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 cluster
Adil Mehmoood
 
diseases caused by computer
diseases caused by computerdiseases caused by computer
diseases caused by computer
Adil Mehmoood
 
Diseases caused by Computer
Diseases caused by ComputerDiseases caused by Computer
Diseases caused by Computer
Adil 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 resume
Adil 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
 
Ad

Recently uploaded (20)

SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 

Swing and AWT in java

  • 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