0% found this document useful (0 votes)
23 views74 pages

Swing Introduction Unit-4-5

Uploaded by

amarnadh115
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views74 pages

Swing Introduction Unit-4-5

Uploaded by

amarnadh115
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 74

Swing Introduction

Swing In Java

• Swing in java is part of Java Foundation Class(JFC) which is


lightweight and platform independent.
• It is used for creating window based applications.
• It includes components like button, scroll bar, text field etc.
• Putting together all these components makes a Graphical
User Interface(GUI).
Java GUI History
• Abstract Windowing Toolkit (AWT): Sun's initial effort to
create a set of cross-platform GUI classes. (JDK 1.0 - 1.1)
– Maps general Java code to each operating system's real GUI
system.
– Problems: Limited to lowest common denominator; clunky to use.
• Swing: A newer GUI library written from the ground up that allows
much more powerful graphics and GUI construction. (JDK 1.2+)
– Paints GUI controls itself pixel-by-pixel rather than handing off to
OS.
– Benefits: Features; compatibility; OO design.

– Problem: Both exist in Java now; easy to get them


mixed up; still have to use both in various places.
GUI terminology
• window: A first-class citizen of the graphical desktop.
– Also called a top-level container.
– examples: frame, dialog box, applet

• component: A GUI widget that resides in a window.


– Also called controls in many other languages.
– examples: button, text box, label

• container: A logical grouping for storing components.


– examples: panel, box
Components
Outline

• What is Java Swing?


• Container Class
• Difference Between AWT And Swing
• Java Swing Class Hierarchy
• Layout Manager
• Example-Chat Frame
What is Swing In Java?
• Swing in Java is a lightweight GUI toolkit which has a wide
variety of widgets for building optimized window based
applications.
• It is a part of the JFC( Java Foundation Classes).
• It is build on top of the AWT API and entirely written in java.
• It is platform independent unlike AWT and has lightweight
components.
• It becomes easier to build applications since we already have
GUI components like button, checkbox etc.
• This is helpful because we do not have to start from the
scratch.
Container Class
• Any class which has other components in it is called as a
container class. For building GUI applications at least one
container class is necessary.

• Following are the three types of container classes:

1. Panel – It is used to organize components on to a window


2. Frame – A fully functioning window with icons and titles
3. Dialog – It is like a pop up window but not fully functional
like the frame
Difference Between AWT and Swing

AWT SWING
• Platform Dependent • Platform Independent
• Does not follow MVC • Follows MVC
• Lesser Components • More powerful components
• Does not support pluggable • Supports pluggable look and
look and feel feel
• Heavyweight • Lightweight
Java Swing Class Hierarchy
Swing inheritance hierarchy
• Component (AWT)
– Window import java.awt.*;
import javax.swing.*;
• Frame
• JFrame (Swing)
• JDialog

– Container
• JComponent (Swing)
• JButton JColorChooser JFileChooser
• JComboBox JLabel JList
• JMenuBar JOptionPane JPanel
• JPopupMenu JProgressBar JScrollbar
• JScrollPane JSlider JSpinner
• JSplitPane JTabbedPane JTable
• JToolbar JTree JTextArea
• JTextField ...
Component properties
– Each has a get (or is) accessor and a set modifier method.
– examples: getColor, setFont, setEnabled, isVisible
name type description
background Color background color behind component
border Border border line around component
enabled boolean whether it can be interacted with
focusable boolean whether key text can be typed on it
font Font font used for text in component
foreground Color foreground color of component
height, width int component's current size in pixels
visible boolean whether component can be seen
tooltip text String text shown when hovering mouse
size, minimum / Dimension various sizes, size limits, or desired
maximum / preferred size sizes that the component may take
JFrame

a graphical window to hold other components

• public JFrame()
public JFrame(String title)
Creates a frame with an optional title.

– Call setVisible(true) to make a frame appear on the


screen after creating it.

• public void add(Component comp)


Places the given component or container inside the frame.
More JFrame
• public void setDefaultCloseOperation(int
op)
Makes the frame perform the given action when it closes.
– Common value passed: JFrame.EXIT_ON_CLOSE
– If not set, the program will never exit even if the frame is closed.

• public void setSize(int width, int


height)
Gives the frame a fixed size in pixels.

• public void pack()


Resizes the frame to fit the components inside it snugly.
JButton
a clickable region for causing actions to occur

• public JButton(String text)


Creates a new button with the given string as its text.

• public String getText()


Returns the text showing on the button.

• public void setText(String text)


Sets button's text to be the given string.
Simple Java Swing Example
creating one button and adding it on the JFrame object inside the main()
method.
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame

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


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

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

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


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
output
Example of Swing by Association inside
constructor
We can also write all the codes of creating JFrame, JButton and method call inside the
java constructor.
import javax.swing.*;
public class Simple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame

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


b.setBounds(130,100,100, 40);

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


f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
public static void main(String[] args) {
new Simple();
}
}
Java Swing Class Hierarchy
• All the components in swing like JButton, JComboBox, JList,
JLabel are inherited from the JComponent class which can be
added to the container classes.
• Containers are the windows like frame and dialog boxes.
• Basic swing components are the building blocks of any gui
application.
• Methods like setLayout override the default layout in each
container.
• Containers like JFrame and JDialog can only add a component
to itself.
Components with examples
JButton Class
• It is used to create a labelled button. Using the ActionListener
it will result in some action when the button is pushed. It
inherits the AbstractButton class and is platform independent.
import javax.swing.*;
public class example{
public static void main(String args[])
{
JFrame a = new JFrame("example");
JButton b = new JButton("click me");
b.setBounds(40,90,85,20);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
• Output
JTextField Class
• It inherits the JTextComponent class and it is used to allow
editing ofjavax.swing.*;
import single line text
public class example{
public static void main(String args[])
{
JFrame a = new JFrame("example");
JTextField b = new
JTextField("edureka");
b.setBounds(50,100,200,30);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
• Output
JScrollBar Class
• It is used to add scroll bar, both horizontal and vertical.
import javax.swing.*;
class example{
example(){
JFrame a = new JFrame("example");
JScrollBar b = new JScrollBar();
b.setBounds(90,90,40,90);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[]){
new example();
}
}
• Output
JPanel Class
• It inherits the JComponent class and provides space for an
application which can attach any other component.
import java.awt.*;
import javax.swing.*;
public class Example{
Example(){
JFrame a = new JFrame("example");
JPanel p = new JPanel();
p.setBounds(40,70,200,200);
JButton b = new JButton("click me");
b.setBounds(60,50,80,40);
p.add(b);
a.add(p);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[]){
new Example();
}
}
• Output
JMenu Class
• It inherits the JMenuItem class, and is a pull down menu
component which is displayed from the menu bar.
import javax.swing.*;
class Example{
JMenu menu;
JMenuItem a1,a2;
Example(){
JFrame a = new JFrame("Example");
menu = new JMenu("options");
JMenuBar m1 = new JMenuBar();
a1 = new JMenuItem("example");
a2 = new JMenuItem("example1");
menu.add(a1);
menu.add(a2);
m1.add(menu);
a.setJMenuBar(m1);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[]){
new Example();
}
}
• Output
JList Class
• It inherits JComponent class, the object of JList class
represents a list of text items.
import javax.swing.*;
public class Example
{
Example(){
JFrame a = new JFrame("example");
DefaultListModel<String> l = new
DefaultListModel< >();
l.addElement("first item");
l.addElement("second item");
JList<String> b = new JList< >(l);
b.setBounds(100,100,75,75);
a.add(b);
a.setSize(400,400);
a.setVisible(true);
a.setLayout(null);
}
public static void main(String args[]){
new Example();
}
}
• Output
JLabel Class
• It is used for placing text in a container. It also inherits
JComponent class.
import javax.swing.*;
public class Example{
public static void main(String args[])
{
JFrame a = new JFrame("example");
JLabel b1;
b1 = new JLabel("edureka");
b1.setBounds(40,40,90,20);
a.add(b1);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
}
• Output
JComboBox Class
• It inherits the JComponent class and is used to show pop up
menu of choices.
import javax.swing.*;
public class Example{
JFrame a;
Example(){
a = new JFrame("example");
string courses[] = { "core java","advance java", "java servlet"};
JComboBox c = new JComboBox(courses);
c.setBounds(40,40,90,20);
a.add(c);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[]){
new Example();
}
}
• Output
Sizing and positioning
How does the programmer specify where each component appears,
how big each component should be, and what the component should
do if the window is resized / moved / maximized / etc.?

• Absolute positioning (C++, C#, others):


Programmer specifies exact pixel coordinates of every component.
– "Put this button at (x=15, y=75) and make it 70x31 px in size."

• Layout managers (Java):


Objects that decide where to position each component based on
some general rules or criteria.
– "Put these four buttons into a 2x2 grid and put these text boxes in
a horizontal flow in the south part of the frame."
Containers and layout
• Place components in a container; add the container to a frame.
– container: An object that stores components and governs their
positions, sizes, and resizing behavior.
JFrame as container
A JFrame is a container. Containers have these methods:

• public void add(Component comp)


public void add(Component comp, Object info)
Adds a component to the container, possibly giving extra information
about where to place it.

• public void remove(Component comp)

• public void setLayout(LayoutManager mgr)


Uses the given layout manager to position components.

• public void validate()


Refreshes the layout (if it changes after the container is onscreen).
Preferred sizes
• Swing component objects each have a certain size they would "like"
to be: Just large enough to fit their contents (text, icons, etc.).
– This is called the preferred size of the component.

– Some types of layout managers (e.g. FlowLayout) choose to


size the components inside them to the preferred size.
– Others (e.g. BorderLayout, GridLayout) disregard the
preferred size and use some other scheme to size the
components.

Buttons at preferred size: Not preferred size:


Layout Manager
• To arrange the components inside a container we
use the layout manager. Following are several
layout managers:
1.Border layout
2.Flow layout
3.GridBag layout
BorderLayout

public BorderLayout()

• Divides container into five regions:


 NORTH and SOUTH regions expand to fill region horizontally,
and use the component's preferred size vertically.
 WEST and EAST regions expand to fill region vertically,
and use the component's preferred size horizontally.
 CENTER uses all space not occupied by others.
myFrame.setLayout(new BorderLayout());
myFrame.add(new JButton("Button 1"), BorderLayout.NORTH);

 This is the default layout for a JFrame.


Border Layout
• The default layout manager for every JFrame is BorderLayout.
It places components in upto five places which is top, bottom,
left, right and center.
FlowLayout
public FlowLayout()

• treats container as a left-to-right, top-to-bottom "paragraph".


• Components are given preferred size, horizontally and vertically.
• Components are positioned in the order added.
• If too long, components wrap around to the next line.

myFrame.setLayout(new FlowLayout());
myFrame.add(new JButton("Button 1"));

• The default layout for containers other than JFrame (seen


later).
Flow Layout
• FlowLayout simply lays the components in a row one after the
other, it is the default layout manager for every JPanel.
GridLayout

public GridLayout(int rows, int columns)

• Treats container as a grid of equally-sized rows and columns.


• Components are given equal horizontal / vertical size, disregarding
preferred size.
• Can specify 0 rows or columns to indicate expansion in that direction
as needed.
GridBag Layout
• GridBagLayout places the components in a grid which allows
the components to span more than one cell.
Example: Chat Frame
import javax.swing.*;
import java.awt.*;
class Example {
public static void main(String args[]) {

JFrame frame = new JFrame("Chat Frame");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLO
SE);
frame.setSize(400, 400);

JMenuBar ob = new JMenuBar();


JMenu ob1 = new JMenu("FILE");
JMenu ob2 = new JMenu("Help");
ob.add(ob1);
ob.add(ob2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 = new JMenuItem("Save as");
ob1.add(m11);
ob1.add(m22);
JPanel panel = new JPanel(); // the panel is not visible in
output
JLabel label = new JLabel("Enter Text");
JTextField tf = new JTextField(10); // accepts upto 10
characters
JButton send = new JButton("Send");
JButton reset = new JButton("Reset");
panel.add(label); // Components Added using Flow
Layout
panel.add(label); // Components Added using Flow
Layout
panel.add(tf);
panel.add(send);
panel.add(reset);
JTextArea ta = new JTextArea();

frame.getContentPane().add(BorderLayout.SOUTH,
panel);
frame.getContentPane().add(BorderLayout.NORTH, tf);
frame.getContentPane().add(BorderLayout.CENTER, ta);
frame.setVisible(true);
}
}
output
Event Listeners
Graphical events
• event: An object that represents a user's interaction with a GUI
component; can be "handled" to create interactive components.

• listener: An object that waits for events and responds to them.


To handle an event, attach a listener to a component.
The listener will be notified when the event occurs (e.g. button
click).
Event-driven programming
• event-driven programming: A style of coding where a program's
overall flow of execution is dictated by events.
 Rather than a central "main" method that drives execution,
the program loads and waits for user input events.
 As each event occurs, the program runs particular code to
respond.
 The overall flow of what code is executed is determined by the
series of events that occur, not a pre-determined order.
Event hierarchy

import java.awt.event.*;

• EventObject • EventListener
– AWTEvent (AWT) – AWTEventListener
• ActionEvent – ActionListener
• TextEvent – TextListener
• ComponentEvent – ComponentListener
– FocusEvent – FocusListener
– WindowEvent – WindowListener
– InputEvent
• KeyEvent – KeyListener
• MouseEvent – MouseListener
Action events
• action event: An action that has occurred on a GUI component.
 The most common, general event type in Swing. Caused by:
 button or menu clicks,
 check box checking / unchecking,
 pressing Enter in a text field, ...

 Represented by a class named ActionEvent


 Handled by objects that implement interface ActionListener
Implementing a listener

public class name implements ActionListener {


public void actionPerformed(ActionEvent event) {
code to handle the event;
}
}

• JButton and other graphical components have this method:


 public void addActionListener(ActionListener al)
Attaches the given listener to be notified of clicks and events that
occur on this component.
Nested classes
• nested class: A class defined inside of another class.

• Usefulness:
 Nested classes are hidden from other classes (encapsulated).
 Nested objects can access/modify the fields of their outer object.

• Event listeners are often defined as nested classes inside a GUI.


Nested class syntax
// enclosing outer class
public class name {
...

// nested inner class


private class name {
...
}
}

 Only the outer class can see the nested class or make objects of it.
 Each nested object is associated with the outer object that
created it, so it can access/modify that outer object's
methods/fields.
• If necessary, can refer to outer object as OuterClassName.this
Static inner classes
// enclosing outer class
public class name {
...

// non-nested static inner class


public static class name {
...
}
}

 Static inner classes are not associated with a particular outer


object.
 They cannot see the fields of the enclosing class.
 Usefulness: Clients can refer to and instantiate static inner classes
Outer.Inner name = new Outer.Inner(params);
GUI event example
public class MyGUI {
private JFrame frame;
private JButton stutter;
private JTextField textfield;

public MyGUI() {
...
stutter.addActionListener(new StutterListener());
}
...

// When button is clicked, doubles the field's text.


private class StutterListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String text = textfield.getText();
textfield.setText(text + text);
}
}
}
The GUI Event Loop
1. GUI application is started
2. Widgets are set up
3. Event loop is started
4. Wait for events from the windowing system
(event queue)
5. Dispatch each event to the right widget
– Input event: call appropriate event handler
( call to application logic)
– Paint event: call paint method
6. Go back to 4.

 Event-Driven Programming

61
Window Manager
• Controls placement and appearance of windows
(but not the window contents)
– Open, close, minimize, maximize, move, resize
– Start apps, list and switch between running apps
– Window decorators, desktop background with icons
• Often built into windowing system
• Implemented using a widget toolkit

62
Introduction to Java Swing

63
Swing Design Principles
• GUI is built as containment hierarchy of widgets
(i.e. the parent-child nesting relation between
them)
• Event objects and event listeners
– Event object: is created when event occurs (e.g. click),
contains additional info (e.g. mouse coordinates)
– Event listener: object implementing an interface with
an event handler method that gets an event object as
argument
• Separation of Model and View:
– Model: the data that is presented by a widget
– View: the actual presentation on the screen
64
Partial AWT and Swing
Class Hierarchy
java.lang.Object

CheckboxGroup Component MenuComponent

Button Canvas Checkbox Choice Container Label List Scrollbar TextComponent

JComponent Scrollpane Panel Window

AbstractButton JLabel JList JPanel JScrollpane Applet Dialog Frame

JButton JApplet JDialog JFrame

java.awt.* javax.swing.* 65
The Initial Swing GUI
Containment Hierarchy
a 3D model
enables menus
Frame / Dialog / Applet to pop up above
the content pane
Root Pane

Layered Pane

File Edit

Undo
Redo
Cut

allows for Content Pane


interception of
mouse events and
painting across
GUI components Glass Pane 66
The Initial Swing GUI
Containment Hierarchy
aTopLevelContainer:
JFrame or JDialog or JApplet

rootPane:
JRootPane

(JPanel) glassPane: layeredPane:


java.awt.Component JLayeredPane optional

(JPanel) contentPane: menuBar:


java.awt.Container JMenuBar
67
Swing Hello World
with Events
...
public class HelloWorld {
public static void main(String[] args) {
...
JButton button = new JButton("Hello World!");
button.addActionListener(new MyActionListener());
...
}
}

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Toolkit.getDefaultToolkit().beep();
}
}
68
Containment Hierarchy

of a Menu
public class MenuExample {
public static void main(String[] args) {
JFrame frame = new JFrame("My Frame");
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE); File Edit
JMenu fileMenu = new JMenu("File");
fileMenu.add(new JMenuItem("New")); New
fileMenu.add(new JMenuItem("Open")); Open
fileMenu.add(new JMenuItem("Close")); Close
JMenu editMenu = new JMenu("Edit");
editMenu.add(new JMenuItem("Undo")); File Edit
editMenu.add(new JMenuItem("Redo"));
editMenu.add(new JMenuItem("Cut")); Undo
Redo
JMenuBar menubar = new JMenuBar();
Cut
menubar.add(fileMenu);
menubar.add(editMenu);
frame.setJMenuBar(menubar);
frame.setVisible(true); 69
} }
Handling Menu Events
...
public class MenuExample {
static JFrame frame;
public static void main(String[] args) {
...
JMenuItem item = new JMenuItem("Close");
item.addActionListener(new MenuActionListener());
fileMenu.add(item);
...
} }

...
public class MenuActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(MenuExample.frame,
"Got an ActionEvent at " + new Date(e.getWhen())
+ " from " + e.getSource().getClass());
} } 70
Defining Event Listeners with Anonynous
Classes
...
public class MenuExample {
public static void main(String[] args) {
final JFrame frame = new JFrame("My Frame");
...
JMenuItem item = new JMenuItem("Close");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showOptionDialog(frame,...
}
});
...
} }

• Use new Classname() {…} or new Interfacename(){…} to


create a single object of an anonymous subclass of the given
class/interface
• Anonymous classes can access final variables of their context (i.e.
final variables of the method or class they are created in) 71
Different Kinds of
Swing Events
Low-level events
• MouseEvent: Component got mouse-down, mouse-move, etc.
• KeyEvent: Component got key-press, key-release, etc.
• ComponentEvent: Component resized, moved, etc.
• ContainerEvent: Container's contents changed because a component
was added or removed
• FocusEvent: Component got focus or lost focus
• WindowEvent: Window opened, closed, etc.

High-level semantic events


• ActionEvent: Main action of control invoked (e.g. JButton click)
• AdjustmentEvent: Value was adjusted (e.g. JScrollBar moved)
• ItemEvent: Item was selected or deselected (e.g. in JList)
• TextEvent: Text in component has changed (e.g in JTextField)

72
Events, Listeners, Adapters and
Handler Methods
Event Listener / Handler Methods
Adapter
ActionEvent ActionListener actionPerformed
AdjustmentEvent AdjustmentListener adjustmentValueChanged
MouseEvent MouseListener mouseClicked
MouseAdapter mouseEntered
mouseExited
mousePressed
mouseReleased
KeyEvent KeyListener keyPressed
KeyAdapter keyReleased
keyTyped
ComponentEvent ComponentListener componentShown
ComponentAdapter componentHidden
componentMoved
componentResized
Adapter classes with empty methods for Listener interfaces with >1 methods
73
Summary
• Desktop environments consist of:
– Windowing System: handles input/output
– Widget Toolkit:
draws widgets and dispatches their events
– Window Manager: takes care of windows
• Swing is a widget toolkit for Java
– GUI as containment hierarchy of widgets
– Event objects and event listeners

References:
http://java.sun.com/docs/books/tutorial/uiswing/
http://www.javabeginner.com/java-swing-tutorial.htm
74

You might also like