Вы находитесь на странице: 1из 42

APJ-I, Session 1

Click to edit Master subtitle style

Module 1: Introduction to SWING

FPT APTECH COMPUTER EDUCATION HANOI

Objectives

APJ_I / Session1

22

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)

APJ_I / Session1

33

Abstract Window Toolkit (AWT) -1

Abstract Window Toolkit (AWT) was the only library available to develop GUI based applications These components can be used to create a GUI based standalone application or applets The AWT components were based on peer-components

APJ_I / Session1

44

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 native components.

APJ_I / Session1

55

Benefits of Swing over AWT

Swing components are lightweight as compared to AWT components. 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 be changed Swing components don't have to be rectangular Swing is based on the Model-View-Controller Architecture

APJ_I / Session1

66

MVC Architecture

Model-View-Controller Architecture (MVC) decomposes the application into three layers: The Model represents all the data and the various states of the component The View depicts the graphical part on the screen. The Controller is responsible for determining whether the component should react to any input events from input devices such as the keyboard or mouse.

APJ_I / Session1

77

Separable Model Architecture

Almost all modern user interface frameworks combine the View and Controller, whether they are based on SmallTalk, C++, or even Java Swing. Swing packages each component's View and Controller into an object called a User Interface (UI) delegate. For this reason Swing's underlying architecture is more accurately referred to as Separable Model Architecture or the Model- Delegate Architecture rather than Model-View-Controller Architecture. Ideally communication between both the Model and the UI Delegate is indirect, allowing more than one Model to be associated with one UI Delegate, and vice versa.

APJ_I / Session1

88

Overview of Container

A Container is meant to contain components. There are two types of containers: top-level containers and generalpurpose containers.

APJ_I / Session1

99

The root pane -1

The root pane has four parts Glass Pane, Layered Pane, Content Pane and Menu 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 the other parts of the root pane. It's completely transparent unless one implements the glass pane's paintComponent () method so that it displays something.

APJ_I / Session1

1010

The root pane Layered Pane

Serves to position its contents, which consist of the Content Pane and the optional 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.

APJ_I / Session1

1111

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 inherits from 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 to the content pane.

APJ_I / Session1

1212

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.

Distributed computing in APJ_I / Session1 Java Module 1

1313

General-purpose

The general-purpose containers are used to add other lightweight components like JButton, and JTextField. Eventually the general -purpose containers are added to a top-level container. The various general-purpose containers have different functionality depending on their use, for example a JPanel is an intermediate container to group components.

APJ_I / Session1

1414

JFrame -1

A JFrame is a top-level Container used to create a GUI-based application. It is available in the javax.swing package. A Swing based GUI application can be developed by using two distinct approaches:
Extending javax.swing.Jframe public class WinApp extends JFrame { // Instance Data... public WinApp() { // } public static void main(String[] args){ WinApp app = new WinApp(); } } Declaring javax.swing.Jfrarne public class WinApp extends SomeOtherClass{ // Instance Data public static void main(String[] args) { JFrame frame = new JFrame(); } }

APJ_I / Session1

1515

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 following method: frmWindow.setDefaultCloseOperation(JFrame.EXIT_0N_CL0SE);

Note that components cannot be added to the JFrame directly. They have to be added to the content-pane of JFrame.
APJ_I / Session1 1616

JApplet

An Applet is a Java program which is meant to run as part of a web-page. While using Swing, the javax. applet. JApplet class is used to create an Applet. Once created this Applet is embedded in the web page with the <applet> tag. The methods of JApplet class are:

init() start() paint() stop() destroy() public class MyApplet extends JApplet { public void init() { // } public void start() { // } }
Distributed computing in APJ_I / Session1 Java Module 1

1717

JPanel -1

The JPanel class is both a container and a component. Other components like JButton, JTextField and so on can be added to JPanel. JPanel in turn is added to a top-level container, or even another 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-level container is more advantageous than adding components directly.

APJ_I / Session1

1818

JPanel -2

A JPanel instance is created by invoking its default constructor. The default layout manager of JPanel is FlowLayout. By default the JPanel as a component is import javax.swing.JPanel; JPanel myPanel; visible. You can make it invisible by using myPanel = new JPanel(); the setVisible (boolean) method. If boolean parameter is set to true, JPanel is visible else it isSession1visible. 1919 APJ_I / not

Lightweight Components

Swing components are referred to as lightweight components. Lightweight components render (draw) themselves with pure Java code. The advantages of Lightweight components are that they do not consume extra overheads in terms of memory and execution time. They are platform independent. Their 'Pluggable-Look-And-Feel capabilities allow to virtually copy the look and feel of any operating system on other operating systems. All the Lightweight components in the javax.swing package start with the letter J, like JButton, JTextField and so on. APJ_I / Session1 2020

JLabel

The JLabel is a component to display static text in a GUI-based application. A JLabel can also display an icon, or both text and icon. public String getText(); public void setText(String label);

APJ_I / Session1

2121

Delegation Event Model

The model for event processing in version 1.0 of the AWT is based on inheritance. In order for a program to catch and process GUI events, it must subclass GUI components 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

JButton - 1

A JButton is a rectangular component with a text or icon as its label, and can fire an event when clicked with a mouse.

Imagelcon icon = new Imagelcon("/images/ok.gif"); // Create a button with an image on it. JButton lblName = new JButton("Name", icon); // Add the button to a container getContentPane().add(lblName);
Distributed computing in APJ_I / Session1 Java Module 1

2323

JButton - 2

Since JButton is a Swing component, the Event-Delegation Model is used to 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 actioncode, and this code is specified in the actionPerformed() method. The JButton has a method addActionListener(), which is used to register the listener object. btnMyAction.addActionListener(new MyActionListener())

APJ_I / Session1

2424

JCheckbox

The JCheckBox component creates a component which can have only two states(checked,unchecked) JCheckBox provides a convenient way to perform multiple selections of choices. The choices of JCheckBox are not mutually exclusive. A user can select none, all, or any combination boolean isSelected() void setSelected( boolean state) Add ItemListener
JCheckBox chkBold; chkBold = new JCheckBox {"Bold"); container.add(chkBold); // Anonymous Class chkBold.addltemListener{new ItemLi3tener{) { public void iteiriScateChanged (ItemEvent e) { // Action Code } }

APJ_I / Session1

2525

JRadioButton -1

The JRadioButton component creates a component which can have only two 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)

APJ_I / Session1

2626

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 a JRadioButton 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 the delegation

radPlain.addltemListener(new ItemListener() { public void iternStateChanged (ItemEvent e) { // Action Code } }. APJ_I / Session1 2727

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 a JTextField programmatically. A JLabel and a JTextField go hand-in-hand in most data-entry forms, for the user 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.

APJ_I / Session1

2828

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 a JTextArea prograrnmatically.

APJ_I / Session1

2929

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 programmatically changed to any other character desired. Important methods
public char[] getPassword() public void setText(String text) public void setEchoChar(char c)

A JPasswordField listens for events using Java.awt.event.ActionListener interface It has the method addActionListener ()to register a listener-object, and if registered the when the user presses the 'Enter' key in their JPasswordFieid the control is delegated to the method actionPerformed().

APJ_I / Session1

3030

Common Methods of Swing Components


setIcon() is used to set the icon image of a component setMnemonic() . Mnemonics allows one character in the components label to 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()

APJ_I / Session1

3131

Pluggable look and feel

Pluggable Look and Feel feature enhances the look and behavior of the GUI elements in an application Appearance of GUI components is referred as the look Behavior of GUI component is referred as the feel Multiple look and feels are enabled in Swing architecture by separating every component into two distinct classes

JComponent subclass

APJ_I / Session1

3232

Pluggable look and feel

Look and feels provided by Suns Java Runtime Environment (JRE) are:

CrossPlatformLookAndFeel: is same as the Java L&F and is same across all platforms SystemLookAndFeel: is native to the system on which it is running Synth: allows the user to create their own look and feel with an XML file Multiplexing: allows you to extend the capabilities of user interface created in Swing without having the need to create a new look and feel at the same time
APJ_I / Session1
3333

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 are stored in UIDefaults table that can be easily customized Easy to skin - since all colors, fonts, borders, and painters are available in UIDefaults table, these values can be used
APJ_I / Session1
3434

Activating Nimbus L&F

Three ways by which Nimbus L&F can be activated are:


Using UIManager class

Invoke the setLookAndFeel() method from the UIManager class to set the Nimbus L&F present in javax.swing.plaf.nimbus.NimbusLookAndFeel package Snippet

... try { UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (Exception e) { // handle exception } ...

APJ_I / Session1

3535

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

Snippet
... #Swing properties swing.defaultlaf = javax.swing.plaf.nimbus.NimbusLookAndFeel ...

Using Command Line option


Set the Nimbus L&F from the command line Snippet

java -Dswing.defaultlaf=com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel

APJ_I / Session1

3636

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 to maintain a Swing L&F

APJ_I / Session1

3737

UIManager Class [2-3]

Commonly used method of the UIManager class is getInstalledLookAndFeels()


Method returns an array of objects of the available LookAndFeelInfo class LookAndFeelInfo class is a static nested class of UIManager class LookAndFeelInfo class provides information on installed look and feels

APJ_I / Session1

3838

UIManager Class [3-3]


Snippet
... for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } ...

getInstalledLookAndFeels() method returns an array of available look and feel class names if condition checks whether the class name retrieved is equal to Nimbus setLookAndFeel() method sets the current look and feel to Nimbus
APJ_I / Session1
3939

Summary

The JFC is graphical framework which includes the older AWT, Swing and Java2D. Swing is framework based on the Model-View-Controller architecture MVC Architecture decomposes the above three functionality into three distinct 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.

APJ_I / Session1

4040

Next

We are going to learn about


LayoutManager to manage Compoenent on Container Component Swing Menu Components

APJ_I / Session1

4141

References

The Java Tutorials Using Swing Components Java Swing Tutorial OReilly: Java Swing, 2nd Edition APJ_I Class Notes

APJ_I / Session1

4242

Вам также может понравиться