FPT APTECH COMPUTER EDUCATION HANOI Click to edit Master subtitle style APJ-I, Session 1 Module 1: Introduction to SWING
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 1/42
FPT APTECH COMPUTER EDUCATION HANOI
Click to edit Master subtitle style
APJ-I, Session 1
Module 1: Introduction to SWING
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 2/42
APJ_I / Session1
Objectives
22 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 3/42
APJ_I / Session1
What is Swing?
• Java Foundation Classes (JFC)
is a graphical framework
which includes the older
Abstract Window Toolkit (AWT),
Swing and Java2D classes.• Swing supports a technology called
'Pluggable-Look-And-Feel' (PLAF)
33 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 4/42
APJ_I / Session1
Abstract Window Toolkit (AWT) -1
• Abstract Window Toolkit (AWT) was the only libraryavailable to develop GUI based applications
• These components can be used to create a GUI basedstandalone application or applets
• The AWT components were based on peer-components
44 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 5/42
APJ_I / Session1
Abstract Window Toolkit (AWT) -2
• The peer-component
dependency made the AWT
components heavy as memory
consumption and operational
performance was considered.• Hence, they were referred to
as heavy-weight components
•
AWT components would always have the 'look and feel' of the nativecomponents.
55 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 6/42
APJ_I / Session1
Benefits of Swing over AWT
• Swing components are lightweight as compared to AWTcomponents.
• Swing components are visually appealing.• Swing components have more capabilities than AWT
components: – Buttons and Labels can display images – Borders drawn around most of the Swing components can be
changed. –
The behavior or appearance of a Swing component can bechanged – Swing components don't have to be rectangular – Swing is based on the Model-View-Controller Architecture
66 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 7/42 APJ_I / Session1
MVC Architecture
• Model-View-Controller Architecture (MVC) decomposes the application intothree layers:
– The Model represents all the data and the various states of thecomponent
– The View depicts the graphical part on the screen. –
The Controller is responsible for determining whether the componentshould react to any input events from input devices such as thekeyboard or mouse.
77 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 8/42 APJ_I / Session1
Separable Model Architecture
• Almost all modern user interface frameworks combine the View andController , whether they are based on SmallTalk, C++, or even JavaSwing.
• Swing packages each component's View and Controller into an objectcalled a User Interface (UI) delegate. For this reason Swing's underlying
architecture is more accurately referred to as Separable ModelArchitecture or theModel- Delegate Architecturerather than Model-View-Controller Architecture.
• Ideally communication between
both the Model and the UI Delegateis indirect, allowing more thanone Model to be associated withone UI Delegate, and vice versa.
88 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 9/42 APJ_I / Session1
Overview of Container
• A Container is meant to contain components.
• There are two types of containers: top-level containers and general-purpose containers.
99 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 10/42
APJ_I / Session1
The root pane -1
• The root pane has four parts Glass Pane, Layered Pane, Content Pane andMenu Bar.
• A glass pane is hidden by default.
• If the glass pane is made visible, then it's like a sheet of glass over all theother parts of the root pane.
•
It's completely transparent unless one implements the glass pane'spaintComponent () method so that it displays something.
1010 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 11/42
APJ_I / Session1
The root pane – Layered Pane
• Serves to position its contents, which consist of the Content Pane and theoptional Menu Bar. It can also hold other components in a specified z -order.
• Each root pane places its menu bar and content pane in an instance of JLayeredPane. The z - ordering that the layered pane provides enables
behavior such as displaying popup menus above other components.
1111 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 12/42
APJ_I / Session1
The root pane - Content Pane
• The Content Pane is the container of the root pane's visible components.Most GUI components are added to this content pane.
• The default content pane is a simple intermediate container that inheritsfrom JComponent, and uses a BorderLayout as its layout manager.
• The object-reference of the content pane of a top-level container is retrieved
by calling the getContentPane 0 method. You then add GUI components tothe content pane.
1212 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 13/42
APJ_I / Session1
The root pane - Menu Bar
•
All top-level containers can, in theory, have a menu bar. In practice,however, menu bars usually appear only in JFrame and in JApplet.• To add a menu bar to a top-level container, a JMenuBar object is
created, populated with menus, and then the set JMenuBar ()method is invoked.
1313Distributed computing in Java – Module 1APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 14/42
APJ_I / Session1
General-purpose
• The general-purpose containers are used to addother lightweight components like JButton, andJTextField. Eventually the general -purposecontainers are added to a top-level container.
• The various general-purpose containers havedifferent functionality depending on their use, for example a JPanel is an intermediate container
to group components.
1414 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 15/42
APJ_I / Session1
JFrame -1
• A JFrame is a top-level Container used to create a GUI-basedapplication. It is available in the javax.swing package.
• A Swing based GUI application can be developed by using twodistinct approaches:
1515
Extending javax.swing.Jframe Declaring javax.swing.Jfrarne
public class WinApp extends JFrame {
// Instance Data...
public WinApp() {
//
}
public static void main(String[]args){
WinApp app = new WinApp();
}
}
public class WinApp extends
SomeOtherClass{
// Instance Data
public static void main(String[]
args) {
JFrame frame = newJFrame();
}
}
APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 16/42
APJ_I / Session1
JFrame -2
• There are three basic things to be carried out on a frame. – Create a frame :JFrame frmWindow = new JFrame("Login"); – Display a frame
frmWindow. setSize(200,200)
frmWindow.setVisible(true); – Close the frame. By default the close operation of the JFrame is not
functional. To provide the close functionality you use the followingmethod:
frmWindow.setDefaultCloseOperation(JFrame.EXIT_0N_CL0SE);
• Note that components cannot be added to the JFramedirectly. They have to be added to the content-pane of JFrame.
1616 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 17/42
APJ_I / Session1
JApplet
• An Applet is a Java program which is meant to run as part of aweb-page. While using Swing, the javax. applet. JApplet classis used to create an Applet. Once created this Applet isembedded in the web page with the <applet> tag.
• The methods of JApplet class are: – init() – start() – paint() – stop() – destroy()
1717Distributed computing in Java – Module 1
public class MyApplet extends JApplet { public void init() {
//} public void start() {
//}
}
APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 18/42
APJ_I / Session1
JPanel -1
• The JPanel class is both a container and a component. Other components like JButton, JTextField and so on can be added toJPanel. JPanel in turn is added to a top-level container, or evenanother JPanel for nesting purposes.
• A JPanel is a rectangular opaque component, without any visible
border by default. However you can add a border for demarcation.Several different types of borders are available.
• Adding components to a JPanel first and then adding it to a top-levelcontainer is more advantageous than adding components directly.
1818 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 19/42
APJ_I / Session1
JPanel -2
•
A JPanel instance is created by invokingits default constructor.
• The default layout manager of JPanel is
FlowLayout.
• By default the JPanel as a component is
visible. You can make it invisible by usingthe setVisible (boolean) method. If
boolean parameter is set to true, JPanel
is visible else it is not visible. 1919
import javax.swing.JPanel;
JPanel myPanel; myPanel = new JPanel();
APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 20/42
APJ_I / Session1
Lightweight Components
• Swing components are referredto as lightweight components.Lightweight components render (draw) themselves with pure Javacode.
• The advantages of Lightweightcomponents are that they do notconsume extra overheads interms of memory and executiontime.
• They are platform independent.
•
Their 'Pluggable-Look-And-Feel‘capabilities allow to virtuallycopy the look and feel of any operating system on other operating systems.
• All the Lightweight components in the javax.swing package start with theletter J, like JButton, JTextField and so on.
2020 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 21/42
APJ_I / Session1
JLabel
• The JLabel is a component to display static text in a GUI-based application. AJLabel can also display an icon, or both text and icon.
• public String getText();
• public void setText(String label);
2121 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 22/42
APJ_I / Session1
Delegation Event Model
•
The model for event processing in version 1.0 of the AWTis based on inheritance. In order for a program to catchand process GUI events, it must subclass GUIcomponents and override either action() or handleEvent()methods.
• Three participants in the event delegation model: – event source: class that broadcasts events – event listeners: classes that receive event notifications – event object : class that describes the event
APJ_I / Session1 2222
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 23/42
APJ_I / Session1
JButton - 1
•
A JButton is a rectangular component with a text or icon as its label, andcan fire an event when clicked with a mouse.
2323Distributed computing in Java – Module 1
Imagelcon icon = newImagelcon("/images/ok.gif");// Create a button with an image on it.JButton lblName = new JButton("Name", icon);// Add the button to a containergetContentPane().add(lblName);
APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 24/42
APJ_I / Session1
JButton - 2
• Since JButton is a Swing component, the Event-Delegation Model is usedto handle its events.
• The JButton component listens using the java.awt.event.ActionListener interface..MyActionListener implement ActionListener{
actionPerformed(){//
}}
• This interface has one method named actionPerformed().What should happen when a button is pressed is specified in the action-code, and this code is specified in the actionPerformed() method.
• The JButton has a method addActionListener(), which is used to register thelistener object.btnMyAction.addActionListener(new MyActionListener())
2424 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 25/42
APJ_I / Session1
JCheckbox
• The JCheckBox component creates a component which can have only twostates(checked,unchecked)
• JCheckBox provides a convenient way toperform multiple selections of choices. Thechoices of JCheckBox are not mutually exclusive. A user can select none, all, or any combination
• boolean isSelected()void setSelected( boolean state)
• Add ItemListener
2525
JCheckBox chkBold;
chkBold = new JCheckBox {"Bold");
container.add(chkBold);
// Anonymous ClasschkBold.addltemListener{new
ItemLi3tener{) {
public void iteiriScateChanged
(ItemEvent e) {
// Action Code
}
}
APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 26/42
APJ_I / Session1
JRadioButton -1
• The JRadioButton component creates a component which can have onlytwo states, either checked or unchecked, by default it is unchecked.JRadioButton radPlain, radBold;
ButtonGroup group;
radPlain = new JRadioButton("Plain", true);
container.add(radPlain);
radBold = new JRadioButton("Bold");
container.add(radBold);
group = new ButtonGroup();
group.add(radPlain);
group.add(radBold);
• The JRadioButton class has methods:ü boolean isSelected()
ü void setSelected(boolean state)
2626 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 27/42
APJ_I / Session1
JRadioButton-2
• A JRadioButton component listens using either java.awt.event.ActionListener or java.awt.event.ItemListener interface.
• The java.awt.event.ItemListener has one method:void itemStateChanged(ItemEvent e)The method itemStateChanged() contains the action code as to what should happen when aJRadioButton component is selected or deselected.
• A JRadioButton has two methods for registering listener-objects namely, addActionListener () and
addltemListener().• If a listener-object is registered with a JRadioButton component, then whenever the component's
state changes from selected to deselected or vice versa, this method is invoked as part of thedelegation
radPlain.addltemListener(new ItemListener() {
public void iternStateChanged (ItemEvent e) {
// Action Code
}
}.
2727 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 28/42
APJ_I / Session1
JTextField
• A JTextField component allows to input and edit a single line of text.Normally text is inputted by the user, however you can also set text in aJTextField programmatically.
• A JLabel and a JTextField go hand-in-hand in most data-entry forms, for theuser to enter textual information.
• The important methods of the JTextFieid are enumerated below:ü String getText() - returns the contents of the JTextField.ü void setText (String text) - programmatically sets the text inü void setEditable (boolean editable) - if false then one cannot type or edit the
contents of the JTextFieid.
2828 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 29/42
APJ_I / Session1
JTextArea
• A JTextArea component allows to input and edit a multiple lines of text.Normally text is entered by the user; however you can also set text in aJTextArea prograrnmatically.
2929 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 30/42
APJ_I / Session1
JPasswordField
• A JPasswordField is similar to a JTextField in appearance. When the user types, the asterisk character (*) is echoed for every character typed.
• By default the asterisk character is echoed, it can be programmaticallychanged to any other character desired.
• Important methods public char[] getPassword ()
public void setText(String text)
public void setEchoChar (char c)
• A JPasswordField listens for eventsusing Java.awt.event.ActionListener interfaceIt has the method addActionListener ()toregister a listener-object, and if registered thewhen the user presses the 'Enter' key in their JPasswordFieid the control is delegated tothe method actionPerformed().
3030 APJ_I / Session1
C f S
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 31/42
APJ_I / Session1
Common Methods of SwingComponents
• setIcon() is used to set the icon image of a component
• setMnemonic() . Mnemonics allows one character in the components labelto be underlined. The component can be either clicked with a mouse or alternately with the Alt key and the mnemonic character combination
• setToolTipText() A Tool Tip is a visual textual feedback from a component
when the mouse cursor hovers over a component.• setBackground() is used to set the background color of the component.
• setForeground() is used to set the foreground color of the component.
• setBorder()
• setEnabled()
•
setFont()• setVisible()
3131 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 32/42
APJ_I / Session1
Pluggable look and feel
• Pluggable Look and Feel feature enhancesthe look and behavior of the GUI elementsin an application
•
Appearance of GUI components is referredas the “look”
• Behavior of GUI component is referred asthe “feel”
• Multiple look and feels are enabled inSwing architecture by separating everycomponent into two distinct classes
–
JComponent subclass –
3232APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 33/42
APJ_I / Session1
Pluggable look and feel
• Look and feels provided by Sun’s JavaRuntime Environment (JRE) are:
– CrossPlatformLookAndFeel: is same as the “JavaL&F” and is same across all platforms
– SystemLookAndFeel: is native to the system onwhich it is running
– Synth: allows the user to create their own lookand feel with an XML file
– Multiplexing: allows you to extend thecapabilities of user interface created in Swingwithout having the need to create a new lookand feel at the same time
3333APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 34/42
APJ_I / Session1
Nimbus Pluggable L&F
• Is a look and feel based on Synth• Provides a polished look to applications• Can be displayed at any resolution•
Is drawn using Java 2D vector graphics• Features of this L&F are:
– Easy customization - colors, icons, and fonts arestored in UIDefaults table that can be easily
customized – Easy to skin - since all colors, fonts, borders, and
painters are available in UIDefaults table, these valuescan be used
3434APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 35/42
APJ_I / Session1
Activating Nimbus L&F
• Three ways by which Nimbus L&F can beactivated are:
• Using UIManager class – Invoke the setLookAndFeel() method from the
UIManager class to set the Nimbus L&F present injavax.swing.plaf.nimbus.NimbusLookAndFeel
package
3535
...try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
// handle exception
}
...
Snippet
APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 36/42
APJ_I / Session1
Activating Nimbus L&F
• Using swing.properties file• Specify the classname as the value for swing.defaultlaf in the
swing.properties file
• Place the file in the <jre install>\lib folder
² Using Command Line option³ Set the Nimbus L&F from the command line
3636
...
#Swing properties
swing.defaultlaf = javax.swing.plaf.nimbus.NimbusLookAndFeel
...
Snippet
java
-Dswing.defaultlaf=com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel
Snippet
APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 37/42
APJ_I / Session1
UIManager Class [1-3]
• Responsible for setting the current Swing L&F• Maintains a set of available look and feel classes• Maintains default values in a table, called
UIDefaults table of Swing components for particular look and feel
• Provides different getter/setter and other accessory methods that enable an application tomaintain a Swing L&F
3737APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 38/42
APJ_I / Session1
UIManager Class [2-3]
• Commonly used method of the UIManager classis getInstalledLookAndFeels()
– Method returns an array of objects of the availableLookAndFeelInfo class
–
LookAndFeelInfo class is a static nested class of UIManager class – LookAndFeelInfo class provides information on installed look
and feels
3838APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 39/42
APJ_I / Session1
UIManager Class [3-3]
• getInstalledLookAndFeels() method returns
an array of available look and feel class names• if condition checks whether the class name retrieved isequal to Nimbus
• setLookAndFeel() method sets the current lookand feel to Nimbus
3939
...
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}...
Snippet
APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 40/42
APJ_I / Session1
Summary
• The JFC is graphical framework which includes the older AWT, Swing andJava2D.
• Swing is framework based on the Model-View-Controller architecture
• MVC Architecture decomposes the above three functionality into threedistinct object: the Model, View and Controller.
•
A Container is meant to contain components. There are two types of Containers, Top-Level Container and General-Purpose Containers.
• Swing provides three top-level Containers JFrarae, JDialog and JApplet.
• There are several general-purpose containers like JPanel, JLayeredPane,JInternalFrame and JDeskTopPane.
• Lightweight components: JButton, JTextField, Jpassword,…
• How to add Action to each component
• How to use the Look&Feel features.
4040 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 41/42
APJ_I / Session1
Next…
• We are going to learn about – LayoutManager to manage Compoenent on
Container Component –
Swing Menu Components
4141 APJ_I / Session1
8/3/2019 Session1 Module1 Intro to Swing
http://slidepdf.com/reader/full/session1-module1-intro-to-swing 42/42
References
• The Java™ Tutorials
• Using Swing Components
• Java Swing Tutorial
• OReilly: Java Swing, 2nd Edition
• APJ_I Class Notes