Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Programming in Java: UNIT-3 (GUI Designing and Event Handling)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 76

Programming in Java

UNIT-3 (GUI Designing and


Event Handling)

Introduction

AWT is fine for developing simple graphical user interfaces, but not for developing
comprehensive GUI projects.

Swing components depend less on the target platform and use less of the native GUI resource.

Swing GUI component classes are named with a prefixed J.

Why AWT and Swing?

Although Swing eliminates a number of the limitations inherent in the AWT, Swing does not
replace it.

Swing is built on the foundation of the AWT. This is why the AWT is still a crucial part of Java.

Swing also uses the same event handling mechanism as the AWT.

Means that they are written entirely in Java and do not map directly to platform-specific peers.

Swing Supports a Pluggable Look and Feel

AWT vs Swing

JFC and Swing

JFC is short for Java Foundation Classes, which encompass a group of features for
building graphical user interfaces (GUIs) and adding rich graphics functionality and
interactivity to Java applications.

Swing GUI Components

Pluggable Look and feel

Which Swing Packages Should I Use?

The Swing API has 18 public packages:

javax.accessibility

javax.swing.plaf

javax.swing.text

javax.swing

javax.swing.plaf.basic

javax.swing.text.html

javax.swing.border

javax.swing.plaf.metal

javax.swing.text.html.parser

javax.swing.colorchooser

javax.swing.plaf.multi

javax.swing.text.rtf

javax.swing.event

javax.swing.plaf.synth

javax.swing.tree

javax.swing.filechooser

javax.swing.table

javax.swing.undo

Classes Required for GUI Programming

The JComponent Class


All Swing components whose names begin with "J" descend from the JComponent
class. For example, JPanel, JScrollPane, JButton, and JTable all inherit from
JComponent. However, JFrame and JDialog don't because they implement top-level
containers.
The JComponent class extends the Container class, which itself extends Component.
The Component class includes everything from providing layout hints to supporting
painting and events. The Container class has support for adding components to the
container and laying them out. This section's API tables summarize the most often
used methods of Component and Container, as well as of JComponent.

Container classes

Helper classes

Using Top-Level Containers

Swing provides three generally useful top-level container classes: JFrame, JDialog, and JApplet.
When using these classes, you should keep these facts in mind:

To appear onscreen, every GUI component must be part of a containment hierarchy. A


containment hierarchy is a tree of components that has a top-level container as its root. We'll
show you one in a bit.

Each GUI component can be contained only once. If a component is already in a container and
you try to add it to another container, the component will be removed from the first container
and then added to the second.

Each top-level container has a content pane that, generally speaking, contains (directly or
indirectly) the visible components in that top-level container's GUI.

You can optionally add a menu bar to a top-level container. The menu bar is by convention
positioned within the top-level container, but outside the content pane.

Using Top-Level Containers

Using Top-Level Containers

Containment hierarchy

As a rule, a standalone application with a Swing-based GUI has at least one


containment hierarchy with a JFrame as its root. For example, if an application
has one main window and two dialogs, then the application has three containment
hierarchies, and thus three top-level containers. One containment hierarchy has a
JFrame as its root, and each of the other two has a JDialog object as its root.

A Swing-based applet has at least one containment hierarchy, exactly one of which
is rooted by a JApplet object. For example, an applet that brings up a dialog has
two containment hierarchies. The components in the browser window are in a
containment hierarchy rooted by a JApplet object. The dialog has a containment
hierarchy rooted by a JDialog object.

Adding Components to the Content Pane

frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
OR

frame. add(yellowLabel, BorderLayout.CENTER);

JFrame

Setting Default operations in a JFrame

setDefaultCloseOperation() is used for setting the default operation for close button of a JFrame.
void setDefaultCloseOperation (int what)

These constants are declared in WindowConstants, which is an interface declared in javax.swing that is
implemented by JFrame.

JFrame.HIDE_ON_CLOSE

JFrame.DO_NOTHING_ON_CLOSE

JFrame.EXIT_ON_CLOSE

Jframe.DISPOSE_ON_CLOSE

DO_NOTHING_ON_CLOSE

Do not do anything when the user requests that the window close. Instead, the program
should probably use a window listener that performs some other action in its windowClosing
method.

HIDE_ON_CLOSE (the default for JDialog and JFrame)

Hide the window when the user closes it. This removes the window from the screen but
leaves it displayable.

DISPOSE_ON_CLOSE (the default for JInternalFrame)

Hide and dispose of the window when the user closes it. This removes the window from the
screen and frees up any resources used by it.

EXIT_ON_CLOSE (defined in the JFrame class)

Exit the application, using System.exit(0). This is recommended for applications only. If
used within an applet, a SecurityException may be thrown.

Swing Containers

The second type of containers supported by Swing are lightweight containers.

Lightweight containers (e.g. JPanel, JScrollPane) do inherit JComponent.

Lightweight containers are used to organize and manage groups of related components because a lightweight
container can be contained within another container.

Thus, we can use lightweight containers to create subgroups of related controls that are contained within an
outer container.

JPanel

JPanel is a generic lightweight container.

Constructors:

JPanel()
Creates a new JPanel with default flow layout.

JPanel(LayoutManager layout)
Create a new JPanel with the specified layout manager.

Swing Components

Swing components are derived from the JComponent class.

JComponent provides the functionality that is common to all components.

For example, JComponent supports the pluggable look and feel.

JComponent inherits the AWT classes Container and Component.

Thus, a Swing component is built on and compatible with an AWT component.

Components

Image Icons

An icon is a fixed-size picture; typically it is small and used to decorate components.

Java supports three image formats: GIF, JPEG, and PNG.

The image file names for these types end with .gif, .jpg, and .png, respectively.

To display an image icon, first create an ImageIcon object using new


javax.swing.ImageIcon(filename).
ImageIcon icon = new ImageIcon (temp.jpg");

An image icon can be displayed in a label or a button using new JLabel(image-Icon) or


new JButton(imageIcon).

Demo Program(ImageDemo.java)

JLabel

JLabel is used to display text and/or an icon. It is a passive component in that it does not
respond to user input.
JLabel()
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)

The align argument specifies the horizontal alignment of the text and/or icon within the
dimensions of the label.

It must be one of the following values: LEFT, RIGHT, CENTER.

JLabel

The icon and text associated with the label can be obtained by the following methods:
Icon getIcon( )

String getText( )

The icon and text associated with a label can be set by these methods:
void setIcon(Icon icon)

void setText(String str)

Demo Program(MyLabel.java)

JTextField

JTextField allows us to edit one line of text.


JTextField()
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)

The integer argument passed to the JTextField constructor, indicates the number of columns in the field
(Minimum number of characters displayed in the TextField).

This number is used along with metrics provided by the field's current font to calculate the field's preferred
width.

It does not limit the number of characters the user can enter.

Demo Program(MyTextfield.java)

JTextArea

A JTextArea is a multi-line area that displays plain text.


JTextArea ()
JTextArea (String str)
JTextArea (int rows, int cols)
JTextField (String str, int rows, int cols)

Demo Program(MyTextArea.java)

JPasswordField

The JPasswordField class, a subclass of JTextField, provides specialized text fields for
password entry.
JPasswordField pf = new JPasswordField(10);

For security reasons, a password field does not show the characters that the user types.

Instead, the field displays a character different from the one typed, such as an asterisk *.
As another security precaution, a password field stores its value as an array of characters,
rather than as a string.

JPasswordField

Setting and Getting Echo-char:


void setEchoChar(char)
char getEchoChar()

Reading the Password:


char[] input = passwordField.getPassword();

Demo Program(MyPasswordField.java)

Swing Buttons

Swing defines four types of buttons, all are subclasses of the AbstractButton class,
which extends JComponent.
JButton,
JToggleButton,
JCheckBox, and
JRadioButton

JButton

JButton class provides the functionality of a push button.

JButton allows an icon, a string, or both to be associated with the push button.
JButton()
JButton(Icon i)
JButton(String str)
JButton(String str, Icon i)

When the button is pressed, an ActionEvent is generated.

We can set the action command by calling setActionCommand( ) on the button.

We can obtain the action command by calling getActionCommand( ) on the event object.

Demo Program(MyButton.java)

JCheckBox

JCheckBox class provides the functionality of a check box.

Its immediate super class is JToggleButton, which provides support for twostate buttons.
JCheckBox(String str)

When the user selects or deselects a check box, an ItemEvent is generated.

JCheckBox

JCheckBox()
Creates an initially unselected check box button with no text, no icon.

JCheckBox(String text)
Creates an initially unselected check box with text

JCheckBox(String text, boolean selected)


Creates a check box with text and specifies whether or not it is initially selected.

JCheckBox

Syntax for setting short cut with alt key from keyboard

JCheckBox generates ItemEvent and ActionEvent

jcb1.setSelected(true);

getSource() returns reference variable of JCheckBox type.

jcb1.isSelected() returns true or false

jcb1.setActionCommand();

jcb2.getActionCommand();

Demo Program(MyCheckBox.java)

Demo Program(MyCheckBoxWithItemEvent.java)

JRadioButton

Radio buttons are a group of mutually exclusive buttons, in which only one button can be
selected at any one time.

They are supported by the JRadioButton class, which extends JToggleButton.

A button group is created by the ButtonGroup class.

Its default constructor is invoked for this purpose.

Elements are added to the button group by using add().

JRadioButton generates action events and item events each time the button selection changes.

JRadioButton

JRadioButton()
Creates an initially unselected radio button with no set text.

JRadioButton(String text)
Creates an unselected radio button with the specified text.

JRadioButton(String text, boolean selected)


Creates a radio button with the specified text and selection state.

Demo Program(MyRadioButton.java)

JList

JList is based on two models.

The first is ListModel. This interface defines how access to the list data is achieved.

The second model is the ListSelectionModel interface, which defines methods that determine what list item or
items are selected.

A JList generates a ListSelectionEvent when the user makes or changes a selection.

JList

It supports the selection of one or more items from a list.


Jlist()
JList(Object [ ] items)

Demo Program(MyList.java)

JComboBox

Combo box is a combination of a text field and a drop-down list.

A combo box normally displays one entry, but it will also display a
drop-down list that allows a user to select a different entry.

JComboBox()
JComboBox(Object[ ]items)

Items can be dynamically added to the list of choices via the addItem( )
method.
void addItem(Object obj)

JComboBox
if (jcb1.getSelectedIndex() != -1)

{
jcb1.getItemAt(jcb1.getSelectedIndex());

jcb.setSelectedIndex(0);

JComboBox

jcb.setForeground(Color.BLUE);

jcb.setFont(new Font("Arial", Font.BOLD, 14));

To limit the maximum number of items displayed in the drop-down list:


jcb.setMaximumRowCount(5);

For adding an item at given position


jcb.insertItemAt("item5", 1);

Demo Program(MyComboBox.java)

JMenu

A menu provides a space-saving way to let the user choose one of several options.

A menu usually appears either in a menu bar or as a popup menu.

A menu bar contains one or more menus.

A popup menu is a menu that is invisible until the user makes a platform-specific mouse
action, such as pressing the right mouse button, over a popup-enabled component.

Creating JMenu

Create a MenuBar

Create Menus

Create MenuItems

Add MenuItems to Menu.

Add Menus to MenuBar

menuBar.add(menu);

Set the MenuBar to the Container

setJMenuBar(menuBar);

JMenuBar menuBar = new JMenuBar();


JMenu menu = new JMenu("File");
JMenuItem mi = new JMenuItem(Open");
menu.add(mi);

Creating a submenu

JMenu submenu=new JMenu("SubMenu");

JMenuItem jsm1=new JMenuItem("SM_OPTION_1");


JMenuItem jsm2=new JMenuItem("SM_OPTION_2");

submenu.add(jsm1);
submenu.add(jsm2);
menuA.add(submenu);

Demo Program(MyComboBox.java)

JScrollPane

JScrollPane is a lightweight container that automatically handles the scrolling of another


component.

The component being scrolled can either be an individual component, such as a table, or a group
of components contained within another lightweight container, such as a JPanel.

The viewable area of a scroll pane is called the viewport. It is a window in which the component
being scrolled is displayed.
JScrollPane(Component comp)

Providing Custom Decorations

Steps to create JScrollPane

Create the component to be scrolled.

Create an instance of JScrollPane, passing to it the object to scroll.

Add the scroll pane to the content pane.

JScrollPane

Provides a scrollable view of a lightweight component. A JScrollPane manages a viewport,


optional vertical and horizontal scroll bars, and optional row and column heading viewports.

JScrollPane does not support heavyweight components.

Setting the Scroll Bar Policy

JScrollPane(Component, int, int)

JScrollPane(int, int)

You can also set the policies dynamically with the setHorizontalScrollBarPolicy and
setVerticalScrollBarPolicy methods.

VERTICAL_SCROLLBAR_AS_NEEDED

HORIZONTAL_SCROLLBAR_AS_NEEDED

VERTICAL_SCROLLBAR_ALWAYS

HORIZONTAL_SCROLLBAR_ALWAYS

VERTICAL_SCROLLBAR_NEVER

HORIZONTAL_SCROLLBAR_NEVER

Demo Program(MyMenuBar.java)

JScrollPane

Any number of these empty spaces can be replaced by using the setCorner
method to add a component to a particular corner.

The same component cannot be added to multiple corners. This is useful if


there's some extra decoration or function you'd like to add to the scroll pane.

The size of each corner component is entirely determined by the size of the
headers and/or scroll bars that surround it.

A common operation to want to do is to set the background color that will be


used if the main viewport view is smaller than the viewport, or is not opaque.

scrollPane.getViewport().setBackground().

By default JScrollPane uses ScrollPaneLayout to handle the layout of its child


Components.

ScrollPaneLayout determines the size to make the viewport view in one of two
ways:

Layout Managers

FlowLayout

GridLayout

BorderLayout

CardLayout

Layout Manager classes

FLowLayout

Properties of Layout Managers

FlowLayout has alignment, hgap, and vgap properties.

You can use the setAlignment, setHgap, and setVgap methods to specify the alignment
and the horizontal and vertical gaps.

GridLayout has the rows, columns, hgap, and vgap properties.

BorderLayout has the hgap and vgap properties.

// Create a layout manager


FlowLayout flowLayout = new FlowLayout();

// Set layout properties


flowLayout.setAlignment(FlowLayout.RIGHT);
flowLayout.setHgap(10);

flowLayout.setVgap(20);

FLowLayout

Demo Program(MyFlowLayout.java)

GridLayout

GridLayout

Demo Program(MyGridLayout.java)

BorderLayout

BorderLayout

Demo Program(MyBorderLayout.java)

CardLayout

It is used to arrange containers in the form of deck of cards.

Methods:
first() / last()/ next()/ previous(): is used to make the first/ last/ next/ previous card visible.
show(): is used to make a specified card visible.
public void show ( Container deck, String CardName)

To give a name to the container while it is added to the deck:


public void add ( Container card, String CardName)

Demo Program(MyCardLayout.java)

Using Panels as Subcontainers

Sample GUI Applications

Color class

We can set colors for GUI components by using the java.awt.Color class.

We can use one of the 13 standard colors (BLACK,

Colors are made of red, green, and blue components, each represented by an int value that describes
its intensity, ranging from 0(darkest shade) to 255 (lightest shade). This is known as the RGB model.

BLUE, CYAN, DARK_GRAY,


GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED,
WHITE, and YELLOW) defined as constants in java.awt.Color.

Color class

We can create a color using the following constructor:


public Color(int r, int g, int b);

Color color = new Color(128,100,100);

The arguments r, g, b are between 0 and 255. If a value beyond this range is passed to the argument, an
IllegalArgumentException will occur.

Example:
JButton jb1 = new JButton("OK");
jb1.setBackground(color);
jb1.setForeground (new Color(100,1,1));

Font class

We can create a font using the java.awt.Font class and set fonts for the components using the setFont method
in the Component class.

The constructor for Font is:


public Font (String name, int style, int size);

You can choose a font name from SansSerif, Serif, Monospaced, Dialog, or DialogInput.

Choose a style from Font.PLAIN(0), Font.BOLD(1), Font.ITALIC(2), and Font.BOLD+Font.ITALIC(3),


and specify a font size of any positive integer.

Font class
Example:
Font font1 = new Font("SansSerif", Font.BOLD, 16);

Font font2 = new Font("Serif", Font.BOLD + Font.ITALIC, 12);


JButton jbtOK = new JButton("OK");
jbtOK.setFont(font1);

MVC Architecture

The model-view-controller (MVC) approach is a way of developing


components by separating data storage and handling from the visual
representation of the data.

The component for storing and handling data, known as a model,


contains the actual contents of the component.

The component for presenting the data, known as a view, handles all
essential component behaviours.

The controller is a component that is usually responsible for obtaining


data, as shown in Figure.

MVC Architecture

It makes multiple views possible so that data can be shared through the
same model. For example, a model storing student names can be
displayed simultaneously in a combo box and a list box.

It simplifies the task of writing complex applications and makes the


components scalable and easy to maintain. Changes can be made to the
view without affecting the model, and vice versa.

MVC Architecture

To achieve consistency and synchronization with its dependent views,


the model should notify the views when there is a change in any of its
properties that are used in the view.

The Java event delegation model provides a superior architecture for


supporting MVC component development.

MVC Architecture example

Events and Event Handling

Event handling and requirement of event handling.

Events are supported by a number of packages, including java.util, java.awt,


and java.awt.event.

Most events to which our program will respond are generated when the user
interacts with a GUI-based program.

They are passed to our program in a variety of ways, with the specific method
dependent upon the actual event. There are several types of events,
including those generated by the mouse, the keyboard, and various GUI
controls, such as a push button, scroll bar, or check box.

Event Delegation Model

The modern approach to handling events is based on the delegation event


model. Its concept is:

a source generates an event and sends it to one or more listeners. In this


scheme, the listener simply waits until it receives an event. Once an event is
received, the listener processes the event and then returns.

The advantage of this design is that the application logic that processes
events is cleanly separated from the user interface logic that generates those
events.

In the delegation event model, listeners must register with a source in order
to receive an event notification. This provides an important benefit:
notifications are sent only to listeners that want to receive them.

Event Delegation Model

Interfaces and Methods for Event Handling


Event Class
ActionEvent

Listener Interface
ActionListener

Listener Methods (Handlers)


actionPerformed(ActionEvent)

ItemEvent

ItemListener

itemStateChanged(ItemEvent)

MouseEvent

MouseListener

mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseClicked(MouseEvent)
mouseExited(MouseEvent)
mouseEntered(MouseEvent)

MouseMotionListener
KeyEvent

KeyListener

mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)

Event Delegation Model

Demo Program(MyMouseListener.java)

Demo Program(MyMouseMotionListener.java)

Demo Program(MyKeyListener.java)

You might also like