java swing tutorial for beginners(java programming tutorials)

darokoblog 3,747 views 66 slides Jul 27, 2014
Slide 1
Slide 1 of 66
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66

About This Presentation

Java programming presentations By Daroko blog
Do not just read java as a programmer, find projects and start making some Money, at DAROKO BLOG,WE Guide you through what you have learned in the classroom to a real business Environment, find java applications to a real business Environment, find also ...


Slide Content

Swing

A Quick Tutorial on Programming
Swing Applications

MVC — Model View Controller

« Swing is based on this design pattern

« lt means separating the implementation of
an application into layers or components:
— The Model - the data structure that
represents something (like a customer info
rec)

— The Controller - the user interface logic for
manipulating it

— The View - the display of that data structure to
the user.

What is Swing?

« A set of classes (part of JFC) that support
platform independent GUI (Graphical User
Interface)

« Successor to the original Java GUI
classes (AWT) which didn’t work very well
(they had platform dependencies that
really made it a difficult API to use)

« AWT wasn't very “sexy”

Swing

« Visible “widgets” - windows, buttons,
combo boxes, trees, tables, checkboxes,
text fields, menus, ...

« Containers of components — applets,
dialogs, windows and frames

« Supporting classes and utility methods

Some important Swing visible
component classes

JApplet **
JButton
JCheckBox
JColorChooser
JComboBox
JDialog **

JFileChooser
JFormattedTextField
JFrame **

JLabel

JList

JMenu

JMenuBar
JMenultem

JPanel

JPasswordField
JPopupMenu
JProgressBar
JRadioButton
JScrollBar
JSlider
JSpinner
JTable
JTextArea
JTextField
JToggleButton
JToolBar
JTree
JWindow **

** means a top level containers

Pogimaná Associates, Inc. (0) 2003 5

Using netbeans to create a
JDialog

adding fields

steps Create Methods

1. Choose Template
New Object Name
Basic Cass Derntion

4 metodo the Methods kt, then fl tin below.

Method:

intComponeriso,
(Overt Iber Methods
Create Methods

closebisloa(ava ant avert WindowEvent)
mana

getCustomerinfoFromPte( Sting)
saveCustomerinfoToFile0

stomerntoToFie

boolean

Peremaler
j'ai

‘String fieNtaneToSaveTo

Ti native

se

eynehronized

Pogimaná Associates, Inc. (0) 2003

my empty
CustomerlnfoDialog:JDialog

code created

Le

ibi ave Customer nfoDialo aja av Jia
{

prints Serie cuneta
primate tong tement D = -1
inte Strg curtemerStete;
te una ester

2092

tic Contamos nfediiegjova.nwt.Frama parent, in

reo

sus ren. mada)
Pi Cemonantaÿ,

=
ES
ES
*
à:
>
rs
bs

osiman & Associates, Inc. (0) 2003

To kill a zombie or running process in
netbeans right click and choose: "terminate”

AA]

Poelman & Associates,

executing the class displays:

Editing a dialog

» 15! select a layout manager for the dialog

edit properties!

<select component

Pogimaná Associates, Inc. (0) 2003

what layout manager should |
use?

« Start with the absolute and then
experiment when you feel comfortable (or
hire a graphic artist and let them worry
about it ;-).

Adding other components to the
view - JTextFields

execute the class

Adding a combo box

edit the model property for the
combo box

AE]

type in state
abbreviations
separated

by commas

customer name

Address

City

Zipcode

Pogimaná Associates, Inc. (0) 2003

preferred size property

or , vert

MVC

Model — View — Controller Design
Pattern

Design Patterns

A design pattern is a way of designing code that benefits from experience of
other developers — see GoF (Gang of Four) on Patterns
Design patterns are “rules of thumb” & best practices
A GUI is based on many design patterns
— 3D Pliancy

Feedback

Icons

Menus

Pointing

Mnemonics 8 Accelerators

Many more ...
A pattern usually has a name (and several aliases), a context, a problem it
addresses, a description of the solution, hints of when to use it and when
not to.
See http://www.csc.calpoly.edu/-dbutler/tutorials/winter96/patterns/ ,
http://choices.cs.uiuc.edu/sane/dpatterns.html#dp and
http://www.stanford.edu/-borchers/hcipatterns

Pogimaná Associates, Inc. (0) 2003

MVC — Model View Controller
pattern
« Swing components are designed as MVC
components

— Model = data or object that is the to be
visually represented

— View = one or more visual representations of
that data/object

— Controller = code to manage input to the
model

View Selection

User Gestures

mm Method invocations

SB BD Events

« © Sun 2002

Pogimaná Associates, Inc. (0) 2003

MVC in Swing Components

The Swing component class is the view
and controller

A separate class is the model

Most components come with a default
model

You can set the model to your own model
for a control

Several controls could share a model!

Fle ast saved: Not Available
Siæ on dk: Not Avaliable
Resoliton’ 81 x81 dete perinch

war [22 E]

inches: Cm Obres

) Black end white

8

OR~ re PR af

Image Colors Hop

Li]

[Bi ERBE 8 85:
CCS in Cnam |

[For eo, clk Hep Tones on th Hab Mer,

2
2

#

>
N
a
o

Pogiman & Associates, Inc. (0) 2003

Creating icons using the blank icon
to start with

Change the properties of the button
to use you icon

Inspector]

Pushing the buttons changes the
displayed prices.

A different and better layout

® NYU Cafe’ UI - Virtual Menu

JFileChooser

Enter Password

¡Button2

E]

JButton

>| a (8 [ca] (es

< JTable
<GPasswordFit

JProgressBar

[Es Logan?
lasrroot

Ac Level Seminars
(A Customers
Filename: [bea

Files of ye: [aies (7

private
private
private
private
private
private
private

private

javax.
javax.
javax.

javax.

javax

javax.
javax.
javax.

javax.

swing.

swing.

swing

swing.
„swing.
swing.
swing.
swing.

swing.

JPasswordField
JTree

Slider
JProgressBar
JTable

Button

jPasswordFieldl;
jTreel;
jSlider1;

jProgressBarl;
jTablel;
jButton2;
jButton1;
jFileChooserl;
jLabell;

Pogimaná Associates, Inc. (0) 2003

Swing based MenuLookDemo

‚A Menu | Another Menu

Atext-onlymenuitem Alt
Both text and icon

radio button menu item
© Another one

(7 A check box menu item
Another one

A sul

Poelman & Associates, Inc. () 2003

TopLevelWindows.java

TopLevelWindows.java

package SwingSamples;
import javax.swing.*;
public class TopLevelWindows
{
public static void main(String args[])
{
JFrame myJFrame = new JFrame("The JFrame");
myJFrame.setSize (300, 300) ;
myJFrame.setLocation (100, 100) ;

JWindow myJWindow = new JWindow () ;
my JWindow.setSize (300, 300) ;
myJWindow.setLocation(500, 100);

myJFrame.setVisible (true) ;
myJWindow.setVisible (true) ;

Poelman & Associates, Inc. () 2003

Top Level Containers

« Must have a top level container in Swing

« You must add components to the
associated content pane

ContentPaneExample. java

package SwingSamples; —
DETTE
import java.awt.*;

import javax.swing.*; Cajas]

With the pack() [one two |

public class ContentPaneExample
{
public static void main(String args{])
{
JFrame myJFrame = new JFrame ("JFrame") ;
my JFrame. setLocation (100,100);

Container myContentPane = myJFrame.getContentPane (); (
myContentPane.setLayout (new FlowLayout ());
myContentPane.add(new JLabel ("One") ) ;
myContentPane.add(new JLabel ("Two") ) ;

myJFrame.pack (); //reformats the layout to the minimum size to fit
everything

myJFrame.setVisible (true) ;

}

Poelman & Associates, Inc. () 2003

ContentPaneExample2.java

package SwingSamples;

import java.awt.*;
import javax.swing.*;

public class ContentPaneExample2
{

public static void main(String args[])

{
JFrame myJFrame = new JFrame ("JFrame");
my JFrame. setLocation (100,100);

Se = von. orassae ME

myContentPane.add(new JLabel ("One"));
myContentPane.add(new JLabel ("Two"));

myJFrame.setContentPane (myContentPane) ; (
myJFrame.pack () ;

myJFrame.setVisible (true) ;

Poelman & Associates, Inc. () 2003

Events

« Swing uses them to communicate
between swing componenis.

« An event is just a method call on the
receiving object by the sending object. The
method passes the event object.

addActionListener (ActionListener listener) ;
removeActionListener (ActionListener listener) ;

« An object registers to receive events. The
method that gets called is:

actionPerformed (ActionEvent e);

Pogimaná Associates, Inc. (0) 2003

Events

In Swing they are multicast — 1 to many
possible. Manes multiple method calls by
the send basically.

Order isn’t defined, though.

Events are immutable to the receiver.
Events may be queued as in the keyboard
event queue.

Multiple events maybe compressed into
one as in mouse movements.

Event Modifier Flags

SHIFT_MASK

CTRL_MASK

META_MASK

ALT_MASK

BUTTON1_MASK

BUTTON2_MASK

BUTTON3_MASK

Detect when certain keys are also pressed.

int modifierFlags = myEvent.getModifiers();

if ((modifierFlags & InputEvent.CRTL_MASK) !=0)
System.println.out (“Pressing the contrl key”);

Pogimaná Associates, Inc. (0) 2003

Event Types

ComponentEvent //resized,moved, shown, hidden
FocusEvent //gained, lost
KeyEvent //typed, pressed, released

MouseEvent //clicked, pressed, released,
//entered, exited

ContainerEvent //componentAdded componentRemoved
ActionEvent //fired by: JButton, JChekBox,
AdjustmentEvent //fired by: JScrollBar

Many more ....

Pogimaná Associates, Inc. (0) 2003

Event Adapter Classes

Map incoming events to a method to invoke on the
model to achieve the function.

Separates the View & Controller from the Model (MVC)
Prebuilt adapter has stubbed out methods for events.
You only implement the ones you are interested. You do
this by extending the adapter and overiding the methods
you need.

Follows a general design pattern of called “adapter”.
MouseAdapter, MouseInputAdapter,
MouseMotionAdapter, KeyAdapter, ComponentAdapter,

ContainerAdapter, DragSourceAdapter,
DropTargetAdapter, FocusAdapter, WindowAdapter, ..

Pogimaná Associates, Inc. (0) 2003

AWT Robot!

« Used to simulate keyboard and mouse
programmatically.

«+ It places events in the native system
queues for the platform you are on (not
just the java queue).

« Used for recording and replaying activities
in regression testing and other uses.

Multithreading and Swing

Swing components always execute on a
single thread within your application. Not
the main thread of your application, either.
Swing components are NOT multithread
safe!

This is done for speed but influences how
you must design for them.

We can ignore this for protoyping Uls but
not for design of applications.

Swing Components

Sample dialog with a few controls.
MySampleOfSwingControlsl.java

JButton

Go

Toggle

Fi Check me
java.lang.Object [7 AndiOr Check me

| © lok te

. No Pick Me!
+--java.awt.Component

Firstitem y]
| First Item |

+--java.awt.Container

|

+--javax.swing.JComponent

+--javax.swing.AbstractButton

+--javax.swing.JButton

Pogimaná Associates, Inc. (0) 2003

JButton

Used for a command
Push and shows a state change visually (pliancy)
Has a name, label text,

Pogimaná Associates, Inc. (0) 2003

Adding items to the List

omy Bona) | ANE Bo ara eae

— ES
5
ges El

Add items to the model for the list

Changing the border of a list box

Cheesecake
French Fries

Turkey Burger
Falafelin Pita
New York Strip Steak:

A Titled Border for a List Box

ae E Turkey Burger
ES ramon

Pogimaná Associates, Inc. (0) 2003

List Box Selection Modes

m fc

oI

« Single

+ Multiple_Interval
« Single_Interval

Setting the Button group on a radio
button

Setting the Mnemonics

Pogimaná Associates, Inc. (0) 2003

Final Dialog Version

Order Burger

‘Burger Customization Dialog - Please select the attributes
and then press the Order Burger button

Tomato
Bacon

Rare
© Medium Rare

Order Burger

Pogimaná Associates, Inc. (0) 2003

JComboBox

+ Two styles in the app — a]
non-editable and editable
If you use the editable
type you should check the
input of the user to make
sure it is acceptable.
You can change the style
by changing the
editable property.

Creating a
JavaGUI -> SampleForms -> Application

E

Menu and Menu item hierarchy that
defines the menus for the app

The default menus

gesea| x

ing] a rs
er
=
fs «nes

sa

Eu E
gras E 02009

All nec PO
ere Roque se

Pogimaná Associates, Inc. (0) 2003

Copy and paste a menu into the
hierarchy

This shows 2 Edit menus

Document Edit View Help