100% found this document useful (2 votes)
175 views

Advanced Java Programming Chapter 3 - GUI Lecture

Uploaded by

Shafi Esa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
175 views

Advanced Java Programming Chapter 3 - GUI Lecture

Uploaded by

Shafi Esa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 184

Chapter 3: Graphical User Interface

Programming

COMPILED BY : HASHIM S(MSC)


Objectives

 By the end of this chapter, you should be able to do the following:


 To write graphical user interface in Java using Swing;

 To create and manipulate components and containers like buttons, labels, lists,
text fields and panels.

 To handle mouse events and keyboard events.

 To use layout managers to arrange GUI components.


Contents

 Overview

 Swing Containers

 Swing Components

 Layout Management

 Event Handling

 Menu Usage

 Font and Color Setting


Overview: Human-Machine Interfaces
 The ways in which a software system interacts with its users.

 Command Line

 Graphical User Interface - GUI

 Multimedia (voice, animation, etc.)

 Intelligent (gesture recognition, conversational, etc.)

 Graphical User Interface - GUI: Visual communication between software and users.
 Besides having a different look and feel from console-based programs, GUI-based programs follow a different
program execution paradigm – event-driven programming.

 A console-based program begins and ends in its main() method. To solve the problem, the main method statements
Overview
 The execution of a GUI-based program also begins in its main() method. Normally the
main method is responsible only for creating an instance of the GUI.

 After creating the GUI, the flow of control passes to an event-dispatching loop that
repeatedly checks for user interactions with the GUI through action events.

 When an event occurs, an action performer method is invoked for each listener of that
event. The performer then processes the interaction.

 After the performer handles the event, control is given again to the event-dispatching loop
to watch for future interactions.

 This process continues until an action performer signals that the program has
completed its task.
Overview
 Computer users today expect to interact with their computers using a graphical user interface (GUI). Java can be
used to write GUI programs ranging from simple applets which run on a Web page to sophisticated stand-alone
applications.

 These interfaces provide the user with multiple windows on the screen and support the use of a mouse to click on
buttons, drag items around, pull down and select items from menus, select text fields in which to type responses,
scroll through windows, and perform many other operations.

 A major part of creating a graphical user interface in Java is figuring out how to position and lay out the
components of the user interface to match the appearance you desire.

 Once you have chosen and laid out these components, you must make the events interactive by making them
respond to various user events such as button clicks or mouse movements.
Overview
 Thus, we will learn to make our interfaces graphical, so we can use our programs through windows, click o
buttons, etc.

 For Java based graphical user interface we have the following packages:

 import java.awt.*;

 import javax.swing.*;

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

Besides, AWT is prone to platform-specific bugs because its peer-based approach relies heavil
on the underlying platform. With the release of Java 2, the AWT user-interface components wer
Overview
 Swing components are painted directly on canvases using Java code, except for components that are subclasses
of java.awt.Window or java.awt.Panel, which must be drawn using native GUI on a specific platform. Swing
components are less dependent on the target platform and use less of the native GUI resource.

 Before Swing, the only option that Java GUI developers had was to use AWT (Abstract Widget Toolkit).
However, because of limitations in AWT, such as the number of components and portability issues, Sun
introduced Swing.

 From a programmer's perspective, Swing is an alternative to using the AWT, although technically Swing
extends (but does not replace) the AWT.

 Swing components that don’t rely on native GUI are referred to as lightweight components, and AWT
components are referred to as heavyweight components.
Overview: AWT Vs. Swing

AWT SWING
 AWT(JDK 1.0, 1.1): Abstract Window Toolkit  Second Edition
 Swing inherits from AWT
 Sun initial idea.
 can be customized
 Not powerful enough.  Allow much power full computer graphics.
 package: java.awt, java.awt.event  Use prefix “J” to differentiate it from awt components and
containers
 heavyweight components using native GUI system
 Swing(Java 2, JDK 1.2+)
elements
 lightweight components that do not rely on the native GUI or OS
 used for applets until most browsers supported JRE 1.2  “look and feel” of Swing components
 are identical on different platforms
 AWT still used for events, layouts
Overview: Some AWT and Swing Classes
Overview: AWT Pros and Cons

Pros Cons
 Portability: use of native peers creates
 Speed: native components speed performance.
platform specific limitations. Some
 Look and feel: AWT components more closely components may not function at all on some
platforms.
reflect the look and feel of the OS they run on.  Features: AWT supports only the lowest
 common denominator—e.g. no tool tips or
Applet Portability: most Web browsers support
icons.
AWT classes so AWT applets can run without  Third Party Development: the majority of
the Java plugin. component makers, including Borland and
Sun, base new component development on
Swing components.
Overview: Swing Pros and Cons
Pros Cons
  Applet Portability: Most Web browsers do not include the Swing
Portability: Pure Java design provides for fewer platform
specific limitations. classes, so the Java plugin must be used.
 Behavior: Pure Java design allows for a greater range of
 Performance: Swing components are generally slower and buggier
behavior for Swing components since they are not limited by
the native peers that AWT uses. than AWT, due to both the fact that they are pure Java and to video
 Features: Swing supports a wider range of features like issues on various platforms. Since Swing components handle their
icons and pop-up tool-tips for components.
own painting (rather than using native API’s like DirectX on
 Vendor Support: Swing development is more active. Sun puts
much more energy into making Swing robust. Windows) you may run into graphical glitches.

 Look and Feel: The pluggable look and feel lets you design a  Look and Feel: Even when Swing components are set to use the look
single set of GUI components that can automatically have the
look and feel of any OS platform (Microsoft Windows, and feel of the OS they are run on, they may not look like their native
Solaris, Macintosh, etc.). It also makes it easier to make counterparts.
global changes to your Java programs that provide greater
accessibility (like picking a hi-contrast color scheme or
changing all the fonts in all dialogs, etc.).
Overview: Swing Stack
 Swing does not replace the AWT; it is built on top of it

 All 1.0 AWT components are heavyweight;


corresponding Swing components are lightweight

 Swing has a much richer and more convenient set of


user interface elements.

 Swing depends far less on the underlying platform; it


is therefore less prone to
platform-specific bugs.
 All this means Swing has the potential of
 Swing will give a consistent user experience across
finally fulfilling the promise of Sun's
platforms. “Write Once,Run Anywhere” slogan.
Overview: Coordinates
 The upper left hand corner of the screen has coordinates (0,0)
 Like the Cartesian system, the value of x increases from left to right (the x-axis goes from left
to right)
 However, the value of y increases from top to bottom (the y-axis goes from top to bottom)
 Measured in pixels (such as 640 by 480)
Overview: GUI Application Creation Stages
1. Design
 Create the containers

 Create and arrange the components

2. Functionality
 Define the user-components interaction

 Attach actions to components

 Create the action handlers

3. Considerations
 Programmatic – Declarative – Visual
Main Steps in GUI Programming
 To make any graphic program work we must be able to create windows and add content to
them.

 To make this happen we must:

1. Import the awt or swing packages.

2. Set up a top-level container.

3. Fill the container with GUI components.

4. Install listeners for GUI Components.

5. Display the container.


GUI Class Hierarchy (Swing)
Dimension Classes in the java.awt
LayoutManager package
Heavyweight
Font 1

FontMetrics

Object Color Panel Applet JApplet

Graphics

Component Container Window Frame JFrame


*
Dialog JDialog

JComponent Swing Components


in the javax.swing package

Lightweight
GUI Class Hierarchy: Container Classes

Dimension Classes in the java.awt


LayoutManager package
Heavyweight
Font 1

FontMetrics

Object Color Panel Applet JApplet

Graphics

Component Container Window Frame JFrame


*
Dialog JDialog

JComponent JPanel Swing Components


Container classes can in the javax.swing package
contain other GUI
components.

Lightweight
GUI Class Hierarchy: Helper Classes

Dimension Classes in the java.awt


LayoutManager package
Heavyweight
Font 1

FontMetrics

Object Color Panel Applet JApplet

Graphics

Component Container Window Frame JFrame


*
Dialog JDialog

The helper classes are not subclasses of Component. They JComponent Swing Components
JPanel
are used to describe the properties of GUI components such in the javax.swing package
as graphics context, colors, fonts, and dimension.

Lightweight
GUI Class Hierarchy: Swing Components

JCheckBoxMenuItem

JMenuItem
JMenu

AbstractButton JButton JRadioButtonMenuItem

JToggleButton JCheckBox

JComponent
JEditorPane JRadioButton Components Covered in the
JTextComponent Comprehensive Version
JTextField JPasswordField

JTextArea

JLabel JList JComboBox JPanel JOptionPane JScrollBar JSlider

JTabbedPane JSplitPane JLayeredPane JSeparator JScrollPane JRootPane

JToolBar JMenuBar JPopupMenu JFileChooser JColorChooser JToolTip

JTree JTable JTableHeader JInternalFrame JProgressBar JSpinner


AWT (Optional)

AWTEvent Container Panel Applet

Font Button Window Frame

FontMetrics Label Dialog FileDialog


TextField
Object Color TextComponent

TextArea
Graphics List

Component Choice

CheckBox

LayoutManager CheckBoxGroup

Canvas

MenuComponent MenuItem Menu

MenuBar
Scrollbar
Simple GUI for I/O with JOptionPane
 The simplest way to create a graphical window in Java is to have an option pane pop up.

 An option pane is a simple message box that appears on the screen and presents a message or a
request for input to the user.

 The Java class used to show option panes is called JOptionPane. JOptionPane belongs to the
javax.swing package, so you’ll need to import this package to use it.

 JOptionPane can be used in three major ways: to display a message, to present a list of choices
to the user, and to ask the user to type input. The three methods that implement these three
behaviors are called showMessageDialog, showConfirmDialog, and showInputDialog,
respectively.
Simple GUI for I/O with JOptionPane
 Message dialog type
 ERROR_MESSAGE A dialog that indicates an error to the user.

 INFORMATION_MESSAGE A dialog with an informational message to the user.

 WARNING_MESSAGE A dialog warning the user of a potential problem.

 QUESTION_MESSAGE A dialog that poses a question to the user. This dialog normally
requires a response, such as clicking a Yes or a No button.

 PLAIN_MESSAGE no icon A dialog that contains a message, but no icon.


Simple JOptionPane example

 import javax.swing.JOptionPane;
 public class AdditionWW{
 public static void main(String[] args){
 String firstnumber= JOptionPane.showInputDialog("Enter First Numbers");
 String secondnumber=JOptionPane.showInputDialog("Enter second Numbers");
 int num1=Integer.parseInt(firstnumber);
 int num2=Integer.parseInt(secondnumber);
 int sum = num1 +num2;
 JOptionPane.showMessageDialog(null,"the sum this two number is ="+sum,"this
result dialog", JOptionPane.PLAIN_MESSAGE);
 }
 }
Containers
 A container is a component which can contain other components inside itself.

 In general components are contained in a container.


 An applet is a container.

 Other containers include windows, frames, dialogs, and panels. Containers may contain
other containers.

 Every container has a LayoutManager that determines how different components


are positioned within the container.

 Components are positioned inside the container according to a LayoutManager.


Containers

 Since containers are themselves components, containers may by placed inside other
containers
 Applets provide a ready-made container and a default LayoutManager, a
FlowLayout.
 Two different kinds of containers:
 Panels: contained inside another container, or perhaps inside the web browser's window.
 Windows: a free-standing, native window.
 There are two kinds of windows:
 Frames: represents a normal, native window.
 Dialogs: a transitory window that exists merely to impart some information or get some
input from the user.
Containers: Windows
 A Frame is what most people think of as a window in their native environment.

 It can have a menu bar;

 it can be independently moved and resized; and

 it will hang around on the screen as long as the user is interested in the content of the window.

 A Dialog will not have a menu bar.

 It can be moved but often can't be resized.

 Its purpose is to get some particular information from the user (input) or to impart some particularly important
information to the user (output).

 It is normally visible on the screen only until it gets the input or receives acknowledgement from the user about its
output.
Windows: Frame
 JOptionPane is useful, but on its own it is not flexible or powerful enough to create rich
graphical user interfaces.
 Frame: A graphical window on the screen. A window with a title bar, a resizable border,
and possibly a menu bar.
 A frame is not attached to any other surface.
 It has a content pane that acts as a container.
 The container uses BorderLayout by default.
 Frames are represented by objects of the JFrame class. Any complex graphical program
must construct a JFrame object to represent its main graphical window.
 Once you’ve constructed a JFrame object, you can display it on the screen by calling its
setVisible method and passing it the boolean value true.
 Component: A widget, such as a button or text field, that resides inside a graphical
window.
Windows: Frame anatomy
 JFrame is the application window class
 It is special; it draws the window and interacts with the operating system
 When a JFrame is created, an inner container called the contentPane is
automatically created
 We don't draw graphics directly on JFrame; we draw on the
contentPane

title bar

minimize
maximize
close

The contentPane holds your content; created automatically


when a JFrame is created
Windows: Frame Properties
 Frame provides the basic attributes and behaviors of a window that you expect
– a title bar at the top of the window, and buttons to minimize, maximize, and
close the window.
 To create a more interesting frame, you’ll have to modify some of the
properties of JFrames. A property of a GUI component is a field or attribute it
possesses internally that you may wish to examine or change.
 A frame’s properties control features like the size of the window or the text
that appears in the title bar. You can set or examine these properties’ values by
calling methods on the frame.
 It turns out that all graphical components and frames share a common set of
properties, because they exist in a common inheritance hierarchy.
Windows: Frame Properties
 To add a component to a frame call the frame's add() method.
f.add(new Button("OK");
 Of course this depends on what class you're inside of when you call add().
 If you're calling add() from one of the Frame subclass's own methods you won't need to
do this.
this.add(new Button(“Ok”);
 Since the default layout for a frame is BorderLayout, you should specify whether you
want the component added to the North, South, East, West or Center.
 The size and position of any given frame is unpredictable unless you specify it.
Specifying the size is easy. Just call the frame's setSize() method like this
f.setSize(150,150);
 This size does not include the title bar so you'll need to account for that separately.
Windows: Frame Properties
 You move a Frame with the setLocation(int x, int y) method. However x and y are
relative to the screen, not to the applet.
 When a window is first created, it's invisible. Add components to the Frame while
it's still invisible.
 The effect of Buttons, Labels and other widgets popping onto a layout in rapid
succession while the window jumps around and changes size can be quite
disconcerting.
 When you're done adding components, resizing and moving the Frame, make it
visible by calling its show() method like so:
f.show(); or f.setVisible(true);
Windows: Frame Properties
 Unlike panels and applets, the default LayoutManager for a frame is
BorderLayout, not FlowLayout.

 However you can change this using the frame's setLayout() method like this:

f.setLayout(new FlowLayout());

 Frames inherit from java.awt.Component so they have paint() and update()


methods.

 If you want to draw in the frame and process events manually, just create a
subclass of Frame and add listener objects to it.
Windows: Frame Example

 The frame is not displayed until the frame.setVisible(true) method is invoked.


frame.setSize(400, 300) specifies that the frame is 400 pixels wide and 300 pixels high.
 If the setSize method is not used, the frame will be sized to display just the title bar. Since the
setSize and setVisible methods are both defined in the Component class, they are inherited by
the JFrame class.
 Later you will see that these methods are also useful in many other subclasses of Component.
Windows: Dialogs
 Dialogs are more transitory. They're used for simple user input or for quick alerts to the user.

 Therefore, a lot of what you learned about frames applies to dialogs as well. You move them,
resize them and add to them almost exactly as you do frames.

 There are two differences between dialogs and frames:

 A frame can have a menu bar. A dialog cannot.

 A dialog can be modal. A frame cannot.

 A modal dialog blocks all other use of the application until the user responds to it.

 A modal dialog cannot be moved and does not allow the user to switch to another window in the
same program.

 On some platforms the user may not even be able to switch to another program
Windows: Dialogs Methods
 Non-modal dialogs pop-up but they don't prevent the user from doing other things while they're
visible.
 Because modal dialogs inconvenience users by forcing them to respond when the computer wants
them to rather than when they want to, their use should be kept to a minimum.
 The only methods that are significantly different between a dialog and a frame are the
constructors.
 There are two constructors for Dialog which differ in whether or not the dialog is given a title.
Dialog d = new Dialog(new Frame( ), false);
 The second argument is a boolean which specifies whether or not the dialog should be modal.
 Modal dialogs are only modal relative to their parent frame, which is passed as the first argument
to the constructor. That is they block input to the parent frame but not to other frames.
Windows: Dialogs Methods
 There are also some common differences between most frames and most dialogs, but these are not
written in stone:

 Most Frames can be moved and resized by the user. Most Dialogs cannot be.

 Most Frames have title bars. Most Dialogs do not.

 You can make a dialog resizable and movable by calling its setResizable() method with a boolean
value of true like this:

d.setResizable(true);

 You can give a dialog a title bar by adding the title string to the constructor:

Dialog d = new Dialog(new Frame(), "My Dialog Window", false);

 All the other methods of the Dialog class are exactly the same as they are for Frames.
Panels as Sub containers
 A panel is a type of container that's designed to hold a group of components so they can be
displayed on a frame.

 The normal way to display a group of controls such as text fields, labels, buttons, and other
GUI widgets is to add those controls to a panel, and then add the panel to the frame.

 You can bypass the panel and add the controls directly to the frame if you want, but using a
separate panel to hold the frames control is almost always a good idea.

 The default layout manager of both Panel and JPanel is FlowLayout, but since they are
containers, they can have any layout manager assigned to them.
Panels as Sub containers
 A Panel is a fairly generic Container whose primary purpose is to subdivide the
drawing area into separate rectangular pieces.

 Since each Panel can have its own LayoutManager, you can do many things with
panels that you can't do with a single LayoutManager.

 Another common use for a panel is to align a series of checkboxes in a


GridLayout with one column.
 A panel can be nested within another panel, a common occurrence when working
with complex GUIs.
Panels as Sub containers: properties
Panels as Sub containers: Example
package panelexample; JButton b2=new JButton("Button 2");

import java.awt.*; b2.setBounds(100,100,80,30);


b2.setBackground(Color.green);
import javax.swing.*;
panel.add(b1);
public class PanelExample {
panel.add(b2);
PanelExample()
f.add(panel);
{ f.setSize(400,400);
JFrame f= new JFrame("Panel Example"); f.setLayout(null);
JPanel panel=new JPanel(); f.setVisible(true);

panel.setBounds(40,80,200,200); }
public static void main(String args[])
panel.setBackground(Color.gray);
{
JButton b1=new JButton("Button 1");
new PanelExample();
b1.setBounds(50,100,80,30); }
b1.setBackground(Color.yellow); }
Components
 GUI’s are built from GUI components. These are sometimes called controls or widgets (short for
windows gadgets) in languages other than Java.

 Many applications that you use on a daily basis use windows or dialog boxes (also called dialogs)
to interact with the user.

 GUI components (sometimes called “widgets”) are items like buttons and menus that can be
added to the user interface to provide a way for users to interact with a program.

 A GUI program offers a much richer type of user interface, where the user uses a mouse and
keyboard to interact with GUI components such as windows, menus, buttons, check boxes, text
input boxes, scroll bars, and so on.
Components
Components: Using a GUI Component
1. Create it
2. Configure it
3. Add children (if container) Order is important

4. Add to parent (if not JFrame)


5. Listen to it

To create a component:
ComponentClassName obj = new ComponentConstructor();
JComponent: The base class for all Swing components except top-level containers
Swing Components
 High-Level Containers  Text Editing Components
JFrame, JDialog, JWindow, JTextField, JFormattedTextField,
JInternalFrame, JApplet JPasswordField, JTextArea,
 JEditorPane, JTextPane
Intermediate Containers
 Menus
JPanel, JScrollPane, JSplitPane,
JTabbedPane, JDesktopPane, JMenuBar, JMenu, JPopupMenu,
JToolBar JMenuItem,
 JCheckboxMenuItem,
Atomic Components JRadioButtonMenuItem
JLabel, JButton, JCheckBox,  Complex Components
JRadioButton, JToggleButton,
JScrollBar, JSlider, JProgressBar, JTable, JTree, JComboBox,
JSeparator JSpinner, JList, JFileChooser,
Label
 The Label component allows for the display of fixed text strings in a container such as a Panel.

 To create a label, use the JLabel class JLabel (which is a subclass of JComponent).

 A typical GUI consists of many components. In a large GUI, it can be difficult to identify the
purpose of every component unless the GUI designer provides text instructions or information
stating the purpose of each component and such text is known as a label.

 A JLabel displays a single line of read-only (noneditable) text, an image, or both text and an
image.
Label
 Labels are used for a variety of purposes:

 to display captions for other controls such as text fields or combo boxes,

 to display informational messages, or

 to show the results of a calculation or a database lookup.

 to display an image, or it can display both an image and some text.

 And you have complete control over the appearance of the text.

 You can specify the font, size, whether the text is bold, italic, or underlined, what color the
text is displayed as, and so on.
Label: Commonly used Constructors:
Constructor Description
JLabel() Creates a JLabel instance with no image and
with an empty string for the title.

JLabel(String s) Creates a JLabel instance with the specified


text.
JLabel(Icon i) Creates a JLabel instance with the specified
image.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified
horizontalAlignment) text, image, and horizontal alignment.
Label: Commonly used Methods:
Methods Description
String getText() It returns the text string that a label
displays.
void setText(String text) It defines the single line of text this
component will display.
void setHorizontalAlignment(int It sets the alignment of the label's
alignment) contents along the X axis.
Icon getIcon() It returns the graphic image that the
label displays.
int getHorizontalAlignment() It returns the alignment of the label's
contents along the X axis.
Label: Example
package labelexample;
import javax.swing.*;
class LabelExample {
public static void main(String args[]) {
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1);
f.add(l2);
f.setSize(300,300);
f.setLayout(null);
Button
 JButton is the most commonly used component and used to create a button the user can click.

 You can either create an empty button or a button with text.

 Buttons are created with the constructor:

JButton()

JButton(String label)

 Methods

 String getText (): - Returns the text displayed by the button.

 void setEnabled (boolean value): - Enables or disables the button. The default setting is true (enabled).

 void setText (String text): - Sets the text displayed by the button.

 void setVisible (boolean value): - Shows or hides the button. The default setting is true (the button is visible).
Button: Example
package buttonexample;

import javax.swing.*;

public class ButtonExample {

public static void main(String[] args) {

JFrame f=new JFrame("Button Example");

JButton b=new JButton("Click Here");

b.setBounds(50,100,95,30);

f.add(b);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

}
Text Fields
 They are single-line areas in which text can be entered by the user from the keyboard or text can
simply be displayed .

 To create a text field, use the JTextField class. An object from the class JTextField displays a single line
of user-updatable text.

 A user may change the contents of a JTextField object by clicking in the field and typing new text. Thus
JTextFields are very useful for obtaining user input.

 Text fields are created using the built-in JTextField class that is part of Java’s Swing package. One
constructor takes an int representing the width of the field in characters (approximately). Others take
an initial string as a parameter or both.

JTextField tf1 = new JTextField(10);

JTextField tf2 = new JTextField("Message");


Text Fields
 Constructors

 JTextField(int columns): - Creates an empty text field with the specified number of columns.

 JTextField(String text): - Creates a text field initialized with the specified text.

 JTextField(String text, int columns): - Creates a text field initialized with the specified text and the column

size.

 Methods

 int getColomns(): - Returns the number of columns of the text field

 setColumns(int): - Sets the number of columns in this text field. The length of the text field is changeable.

 getText(): - Returns the string from the text field.

 setText(String text): - Puts the given string in the text field.


Text Fields:
package textfieldexample;
import javax.swing.*;
class TextFieldExample {
public static void main(String args[]) {
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Java GUI Programming.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT and Swing");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
Password Fields
 JPasswordField is a subclass of the JTextField so it acts like an ordinary text
field but it hides the actual characters typed by showing a series of echo
characters such as asterisks (*) or a dots, for security purposJPasse.

 Constructor
 wordField(String text, int columns) - constructs a new password field.

 Methods
 void setEchoChar(char echo) - sets the echo character for this password field. A value of
0 resets the echo character to the default.

 Char[ ] getPassword() - returns the text contained in this password field.


Password Fields: Example
package passwordfieldexample;
import javax.swing.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
Text Areas
 A JTextArea enables the user to enter multiple lines of text.
 If you want to let the user enter multiple lines of text, you may create several instances of
JTextField. A better alternative is to use JTextArea, which enables the user to enter multiple lines
of text.

 Constructors

 JTextArea( ) - Default constructor - Create an empty text area

 JTextArea(int rows, int columns) - Creates a text area with the specified number of rows and
columns.

 JTextArea(String s, int rows, int columns) - Creates a text area with the initial text and the
number of rows and columns specified.
Text Areas: Example
package textareaexample;
import javax.swing.*;
public class TextAreaExample {
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("This JText Area");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true); }
public static void main(String args[]) {
new TextAreaExample(); }}
Check Box
 If you want to collect just a “yes” or “no” input, use a check box component.

 The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".

 Constructor

 JCheckBox(String label)

 JCheckBox(String label, boolean state)

 JCheckBox(String label, Icon icon)

 Methods

 boolean isSelected ()

 void setSelected(boolean state)


Check Box: Example
package checkboxexample;
import javax.swing.*;
public class CheckBoxExample {
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 100,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true); }
public static void main(String args[]) {
Radio Button
 A Radio Button is different from a Check Box in that there are normally several
Radio Buttons that are grouped together and only one of the Radio Buttons in
the group can be selected (true) at any time.
 To create a radio button, use the JRadioButton class.
 Radio buttons, also known as option buttons, enable you to choose a single item
from a group of choices. In appearance radio buttons resemble check boxes, but
check boxes display a square that is either checked or blank, whereas radio
buttons display a circle that is either filled (if selected) or blank (if not selected).
 Selecting a different radio button in the group automatically forces
all other radio buttons in the group to be deselected.
 The logical relationship between radio buttons is maintained by a
ButtonGroup object (package javax.swing).
JRadioButton Example
Combo Boxes (drop-down list)

 If you have more than a handful of alternatives, radio buttons are not a good choice because
they take up too much screen space.

 A combo box, also known as a choice list or drop-down list, contains a list of items from which
the user can choose.

 A combo box is useful for limiting a user’s range of choices and avoids the cumbersome
validation of data input.

 The first item is added at index 0; The first item added to a JComboBox appears as the
currently selected item when the JComboBox is displayed.

 When clicked, the JComboBox expands into a list from which the user can make a selection.
Combo Boxes (drop-down list)
Commonly used Constructors and Methods
Constructor Description

JComboBox() Creates a JComboBox with a default data model.


JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array.
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specified Vector.

Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox is editable.

void addActionListener(ActionListener a) It is used to add the ActionListener.


void addItemListener(ItemListener i) It is used to add the ItemListener.
Combo Boxes (drop-down list)
Example
package comboboxexample;
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true); }
public static void main(String[] args) {
Lists
 The object of JList class represents a list of text items.
 A list is a component that basically performs the same function as a combo box, but it
enables the user to choose a single value or multiple values.

 Commonly used Constructors:

Constructor Description
JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the


specified array.
JList(ListModel<ary> Creates a JList that displays elements from the
dataModel) specified, non-null, model.
Lists
 Commonly used Methods:
Methods Description
Void It is used to add a listener to the list, to
addListSelectionListener(ListSelectionLis be notified each time a change to the
tener listener) selection occurs.
int getSelectedIndex() It is used to return the smallest selected
cell index.
ListModel getModel() It is used to return the data model that
holds a list of items displayed by the
JList component.
void setListData(Object[] listData) It is used to create a read-only
ListModel from an array of objects.
Lists: Example
package listexample;
import javax.swing.*;
public class ListExample {
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); }
public static void main(String args[]) {

Scroll Bars
The object of JScrollbar class is used to add horizontal and vertical scrollbar. It
is an implementation of a scrollbar. It inherits JComponent class.
 Commonly used Constructors:

Constructor Description
JScrollBar() Creates a vertical scrollbar with the
initial values.
JScrollBar(int orientation) Creates a scrollbar with the specified
orientation and the initial values.
JScrollBar(int orientation, int value, Creates a scrollbar with the specified
int extent, int min, int max) orientation, value, extent, minimum,
and maximum.
Scroll Bars
Example
package scrollbarexample;
import javax.swing.*;
class ScrollBarExample {
ScrollBarExample(){
JFrame f= new JFrame("Scrollbar Example");
JScrollBar s=new JScrollBar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); }
public static void main(String args[]) {
Scroll Pane(Container)
 A JscrollPane is used to make scrollable view of a component. When screen size is limited,
we use a scroll pane to display a large component or a component whose size can change
dynamically.

 The JList component, for example, does not handle scrolling on its own. Instead, it
concentrates on presenting the list and making selection easy, assuming you'll put it inside a
JScrollPane if you need scrolling.

 A similar technique can be used with many of the Swing components, including JPanel,
JTable, and JTextArea.
Scroll Pane(Container)
Constructor Purpose
JScrollPane() It creates a scroll pane. The Component parameter, when
present, sets the scroll pane's client. The two int parameters,
JScrollPane(Component) when present, set the vertical and horizontal scroll bar policies
JScrollPane(int, int) (respectively).
JScrollPane(Component, int, int)

Modifier Method Description


void setColumnHeaderView It sets the column header for the scroll pane.
(Component)
void setRowHeaderView(C It sets the row header for the scroll pane.
omponent)
void setCorner(String, It sets or gets the specified corner. The int parameter specifies which corner and must
Component) be one of the following constants defined in ScrollPaneConstants:
Component getCorner(String) UPPER_LEFT_CORNER, UPPER_RIGHT_CORNER, LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER, LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER, UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.

void setViewportView(Com Set the scroll pane's client.


ponent)
Scroll Pane
Example // set flow layout for the frame
package jscrollpaneexample;
frame.getContentPane().setLayout(new FlowLayout());
import java.awt.FlowLayout;
JTextArea textArea = new JTextArea(20, 20);
import javax.swing.JFrame;
JScrollPane scrollableTextArea = new
import javax.swing.JScrollPane;
JScrollPane(textArea);
import javax.swing.JTextArea; scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.
HORIZONTAL_SCROLLBAR_ALWAYS);
public class JScrollPaneExample {
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VE
private static final long serialVersionUID = 1L; RTICAL_SCROLLBAR_ALWAYS);
private static void createAndShowGUI() { frame.getContentPane().add(scrollableTextArea); }
// Create and set up the window.
public static void main(String[] args) {
final JFrame frame = new JFrame("Scroll Pane Example");
javax.swing.SwingUtilities.invokeLater(new Runnable() {
// Display the window.
public void run() {
frame.setSize(500, 500);
createAndShowGUI(); } }); } }
frame.setVisible(true);
Split Pane(Option, Comp1, Comp2)
 JSplitPane is used to divide two components. The two components are divided based on the look
and feel implementation, and they can be resized by the user. If the minimum size of the two
components is greater than the size of the split pane, the divider will not allow you to resize it.
 The two components in a split pane can be aligned left to right using
JSplitPane.HORIZONTAL_SPLIT, or top to bottom using JSplitPane.VERTICAL_SPLIT.
When the user is resizing the components the minimum size of the components is used to
determine the maximum/minimum position the components can be set to.
 Nested Class:

Modifier and Type Class Description


protected class JSplitPane.AccessibleJSplitPane This class implements
accessibility support for the
JsplitPane class.
Split Pane(Option, Comp1, Comp2)
 Useful Fields
Modifier and Type Field Description
static String BOTTOM It use to add a Component below the other Component.

static String CONTINUOUS_LAYOUT_PROPE Bound property name for continuousLayout.


RTY
static String DIVIDER It uses to add a Component that will represent the
divider.
static int HORIZONTAL_SPLIT Horizontal split indicates the Components are split
along the x axis.
protected int lastDividerLocation Previous location of the split pane.
protected Component leftComponent The left or top component.
static int VERTICAL_SPLIT Vertical split indicates the Components are split along
the y axis.

protected Component rightComponent The right or bottom component.


protected int orientation How the views are split.
Split Pane(Option, Comp1, Comp2)
 Constructors
Constructor Description
JSplitPane() It creates a new JsplitPane configured to arrange the child
components side-by-side horizontally, using two buttons for the
components.

JSplitPane(int newOrientation) It creates a new JsplitPane configured with the specified


orientation.
JSplitPane(int newOrientation, boolean It creates a new JsplitPane with the specified orientation and
newContinuousLayout) redrawing style.
JSplitPane(int newOrientation, boolean It creates a new JsplitPane with the specified orientation and
newContinuousLayout, Component redrawing style, and with the specified components.
newLeftComponent, Component
newRightComponent)
JSplitPane(int newOrientation, It creates a new JsplitPane with the specified orientation and the
Component newLeftComponent, specified components.
Component newRightComponent)
Split Pane(Option, Comp1, Comp2)
 Useful Methods
Modifier and Type Method Description
protected void addImpl(Component comp, Object It cdds the specified component to this split pane.
constraints, int index)
AccessibleContext getAccessibleContext() It gets the AccessibleContext associated with this JSplitPane.

int getDividerLocation() It returns the last value passed to setDividerLocation.


int getDividerSize() It returns the size of the divider.
Component getBottomComponent() It returns the component below, or to the right of the divider.

Component getRightComponent() It returns the component to the right (or below) the divider.
SplitPaneUI getUI() It returns the SplitPaneUI that is providing the current look and
feel.
boolean isContinuousLayout() It gets the continuousLayout property.
boolean isOneTouchExpandable() It gets the oneTouchExpandable property.
void setOrientation(int orientation) It gets the orientation, or how the splitter is divided.
Split Pane(Option, Comp1, Comp2)
Example // set flow layout for the frame

package jsplitpaneexample; frame.getContentPane().setLayout(new FlowLayout());

import java.awt.FlowLayout; String[] option1 = { "A","B","C","D","E" };

JComboBox box1 = new JComboBox(option1);


import java.awt.Panel;
String[] option2 = {"1","2","3","4","5"};
import javax.swing.JComboBox;
JComboBox box2 = new JComboBox(option2);
import javax.swing.JFrame; Panel panel1 = new Panel();

import javax.swing.JSplitPane; panel1.add(box1);

Panel panel2 = new Panel();


public class JSplitPaneExample {
panel2.add(box2);
private static void createAndShow() {
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel2);
// Create and set up the window.
//JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panel1, panel2);

final JFrame frame = new JFrame("JSplitPane Example"); frame.getContentPane().add(splitPane); }

// Display the window. public static void main(String[] args) {

// Schedule a job for the event-dispatching thread:


frame.setSize(300, 300);
// creating and showing this application's GUI.
frame.setVisible(true);
javax.swing.SwingUtilities.invokeLater(new Runnable() {

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); public void run() {

createAndShow(); } }); } }
Tabbed Pane
 A JTabbed Pane arranges GUI components into layers, of which only one is visible at a time.
 When the user clicks a tab, the appropriate layer is displayed.
 Any component can be placed on a tab.
 If the component is a container, such as a panel, it can use any layout manager to lay out several
components on the tab.
 public void addTab(String title, Component comp)
 public void addTab(String title, Icon tabIcon, Component comp)
 public void addTab(String title, Icon tabIcon, Component comp, String tip)
Table
 Tables represent one of the most common formats for viewing data.

 The JTable class is a part of Java Swing Package and is generally used to display or edit two-
dimensional data that is having both rows and columns. It is similar to a spreadsheet.

 This arranges data in a tabular form.

 Rather than adding the table itself directly to our window, we enclose it in a scrollpane:

 Constructors in JTable:

 JTable(): A table is created with empty cells.

 JTable(int rows, int cols): Creates a table of size rows * cols.

 JTable(Object[][] data, Object []Column): A table is created with the specified name where []Column
defines the column names.
Table:
Create the following table
Table: Example
package tableexample; String
import javax.swing.*; column[]={"ID","NAME","SEX","AGE","D
public class TableExample { EPATMENT","CLASS YEAR","GPA"};
JFrame f;
TableExample(){ JTable jt=new JTable(data,column);
f=new JFrame(); jt.setBounds(30,40,200,300);
String data[][]={ JScrollPane sp=new JScrollPane(jt);
{"101","Helen","F","22","Computer Science","3rd f.add(sp);
Year","3.25"},
f.setSize(300,400);
{"102","Melat","F","21","Software Eng","3rd Year","3.02"},
f.setVisible(true);
{"101","Sada","F","23","Information Technology","3rd }
Year","3.6"},
{"101","Hussen","M","23","Information Science","2nd
public static void main(String[] args) {
Year","3.9"}, new TableExample();
{"101","Seid","M","22","Information System","2nd
}
Year","3.7"}
}; }
File Chooser
 A special dialog box that allows the user to select one or more files/folders
 Asking a user to type a path and file name is a bad idea.
 public JFileChooser()
 public JFileChooser(String currentDir)
 public int showOpenDialog(Component parent)
 public int showSaveDialog(Component parent)
 public File getSelectedFile()
 public static int APPROVE_OPTION, CANCEL_OPTION Possible result values from
showXxxDialog(..).
 We want a ‘point and click’ type interface to get a file name.
 JFileChooser myChooser = new JFileChooser();
 myChooser.showOpenDialog(this);
 String file=myChooser.getSelectedFile().toString();
File Chooser Example

public static void main(String[] args) throws Exception{


JFileChooser fileChooser = new JFileChooser();
int a = fileChooser.showOpenDialog(null);

if (a == JFileChooser.APPROVE_OPTION) {
File fileToOpen = fileChooser.getSelectedFile();
Desktop.getDesktop().open(fileToOpen);
}
}
Formatted Text Field

Mask Formatter

Mask Formatter Class


JEditorPane
 JEditorPane is an extension of JTextComponent capable of displaying various types of
content, such as HTML and RTF.

 It is not intended to be used as a full-featured web browser, but it can be used to view simple
HTML and is ideal for integrating online help into Java applications.

Method or Constructor Description


JEditorPane(URL)
JEditorPane(String) Creates an editor pane loaded with the text at the specified URL.

setPage(URL) Loads an editor pane (or text pane) with the text at the specified
setPage(String) URL.
URL getPage() Gets the URL for the editor pane's (or text pane's) current page.
JEditorPane (JEditorPane is a kind of text area
that can display various text formats. )
package jeditorpaneexample;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
public class JEditorPaneExample {
JFrame myFrame = null;
public static void main(String[] a) {
(new JEditorPaneExample()).test(); }
private void test() {
myFrame = new JFrame("JEditorPane Test");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(400, 200);
JEditorPane myPane = new JEditorPane();
myPane.setContentType("text/plain");
myPane.setText("Sleeping is necessary for a healthy body."
+ " But sleeping in unnecessary times may spoil our health, wealth and studies."
+ " Doctors advise that the sleeping at improper timings may lead for obesity during the students days.");
myFrame.setContentPane(myPane);
myFrame.setVisible(true); } }
Tool Bar
 JToolBar container allows us to group other components, usually buttons with icons in a row
or column.

 JToolBar provides a component which is useful for displaying commonly used actions or
controls.

 JToolBar() It creates a new tool bar; orientation defaults to HORIZONTAL.

 JToolBar(int orientation) It creates a new tool bar with the specified orientation.

 JToolBar(String name) It creates a new tool bar with the specified name.

 JToolBar(String name, int orientation) It creates a new tool bar with a specified name and
orientation.
Tool Bar
Layout Management
(Arranging Elements in Windows)
 You may be wondering why we don’t just specify the size and location of
components in the window, as we did with graphics objects on the canvas, rather
than depending on layout managers and panels to arrange them.
 One reason is that the user can resize the window at any time. It would be very
inconvenient to have the user resize the window so that some of the components
were no longer visible.
 Layout management is the process of determining the size and location of a
container's components.
 Java containers do not handle their own layout. They delegate that task to their
layout manager, an instance of another class.
 If you do not like a container's default layout manager, you can change it.
Container content = getContentPane();
content.setLayout( new FlowLayout() );
Layout Management
 When building a GUI, each GUI component must be attached to a container, such as a
window created with a JFrame.
 Typically, you must also decide where to position each GUI component within the container.

 This is known as specifying the layout of the GUI components.


 Layout management proceeds bottom up through the containment hierarchy.
 If a container encloses another container, the enclosing container can not position the inner
container nor size itself until it knows how big the inner container needs to be.
 And the inner container can not size itself until it queries its contents
Layout Management (Preferred Size)
 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
Layout Management
 Layout managers control:
 Where components appear
 What sizes they are
 How they react when they are
resized
 Layout managers control the size and
arrangement of components in a container.
 There are 6 common layout managers:
1. FlowLayout
2. BorderLayout
3. GridLayout
4. GridBagLayout
5. BoxLayout
6. CardLayout
Flow Layout

 The component objects appear in order in which they are added to the container
from left to right until no more component will fit on a row. It then moves to the
next row and continue going left to right.
 A flow layout arranges components in a directional flow one after the other,
moving onto a new line when no more components ft on the current line.
Direction is determined by the container’s componentOrientation property and
may be one of two values:
ComponentOrientation.LEFT_TO_RIGHT or
ComponentOrientation.RIGHT_TO_LEFT
 FlowLayout, the simplest of the managers, simply adds components left to
right until it can fit no more within its container's width.
 It then starts a second line of components, fills that, starts a third, etc.
 Each line is centered in the container
Flow Layout
 FlowLayout respects each component's preferred size and will use it to override a size set by
setSize.

 FlowLayout is the default layout manager for Jpanel

 Flow layout is the default layout manager for AWT and Swing components.

 Constructors

 FlowLayout();

 FlowLayout(int align); //align is a constant left, center or right

 FlowLayout(int align, int hSpace, int VSpace);

 setAlignment(int align); //FlowLayout.LEFT, .CENTER, .RIGHT


Border Layout
 A border layout divides the container into five regions; each region may contain only one
component

 As each component is added to a container with a border layout, the location is specified similar to:
 container.add(component, BorderLayout.CENTER);

 Constructor:
 BorderLayout(int n, int m); //n pixel gaps

 Methods
 void add(Component cp, int region);

 Example: cont.add(btn, BorderLayout.CENTER);

 BorderLayout is the default LayoutManager for the contentpane of a JFrame


Border Layout
Grid Layout
 Creates a grid structure on the container

 Every component in a GridLayout has the same width and height.

 Constructor:
 GridLayout(int row, int col);

 GridLayout(int row, int col, int hSpace, int VSpace);

 Components are added to a GridLayout starting at the top-left cell of the grid
and proceeding left to right until the row is full
 Eg. new GridLayout(4,3);
Grid Bag Layout
 Divides the window into grids, without requiring the components to be the same size.
 Each component managed by a grid bag layout is associated with an instance of
GridBagConstraints.
 The GridBagConstraints specifies:
 How the component is laid out in the display area
 In which cell the component starts and ends
 How the component stretches when extra room is available
 Alignment in cells
Grid Bag Layout
 To describe the layout to the grid bag manager, use the following procedure:
1. Create an object of type GridBagLayout.
 You don’t tell it how many rows and columns the underlying grid has. Instead, the layout manager will
try to guess it from the information you give it later.
2. Set this GridBagLayout object to be the layout manager for the component.
3. For each component, create an object of type GridBagConstraints.
 Set field values of the GridBagConstraints object to specify how the components are laid out within the
grid bag.
4. Finally, add each component with its constraints by using the call
 add(component, constraints);
Grid Bag Layout
 Far more advanced than any of the other layout managers.
 It is flexible layout manager that aligns components both vertically and horizontally, without
requiring that the components be the same size.
 It maintains a dynamic grid of cells where components can be placed and where the components
can occupy one or more of the cells.
 Constructor:
 public GridBagLayout()
 Constraints:
 gridx, gridy
 gridwidth, gridheight
 fill
Grid Bag Layout

• gridwidth 1 The component will occupy a single cell within the layout. fill NONE The component should not resize itself if extra space is
• gridheight 1 The component will occupy a single cell within the layout. available within its region.
gridConstraints.fill = GridBagConstraints.BOTH;
Grid Bag Layout
1. Set the layout, saving a reference to it
 GridBagLayout layout = new GridBagLayout();
 setLayout(layout);
2. Allocate a GridBagConstraints object
 GridBagConstraints constraints = new GridBagConstraints();
3. Set up the GridBagConstraints for component 1
 constraints.gridx = x1;
 constraints.gridy = y1;
 constraints.gridwidth = width1;
 constraints.gridheight = height1;
4. Add component 1 to the window, including constraints
 add(component1, constraints);

5. Repeat the last two steps for each remaining component


Grid Bag Layout
 If we have a GridBagConstraints object named gridConstraints, a control will occupy two
rows and three columns, starting in the second column (gridx = 1) and fourth row (gridy = 3),
with this code:

 gridConstraints.gridx = 1;
 gridConstraints.gridy = 3;
 gridConstraints.gridheight = 2;
 gridConstraints.gridwidth = 3;

 add(component, gridConstraints);
Card Layout
 The CardLayout layout manager is significantly different from the other layouts. Whereas the
other layout managers attempt to display all the components within the container at once, a
CardLayout displays only one component at a time.

 Card Layout is a simple layout manager that treats each component as a card.

 Only one component is visible at a time; the rest is hidden.

 The first component added to the container is visible by default when the container is initially
displayed.

 This manager has a limited practical use. It can be used to create a wizard or a tabbed pane.
Card Layout
Panel cardPanel;

CardLayout layout new CardLayout();
cardPanel.setLayout(layout);
...
cardPanel.add("Card 1", component1);
cardPanel.add("Card 2", component2);
...
layout.show(cardPanel, "Card 1");
layout.first(cardPanel);
layout.next(cardPanel);
Box Layout
 BoxLayout manager is a simple layout manager that organizes components in a column or a row.

 It can create quite sophisticated layouts with nesting.

 BoxLayout is only able to create fixed spaces; therefore, its layouts are not portable.

 Unlike other layout managers, BoxLayout takes a container instance as the first parameter in the
constructor.

 The second parameter determines the orientation of the manager. To create a horizontal box, we
can use the LINE_AXIS constant. To create a vertical box, we can use the PAGE_AXIS
constant.
Box Layout Example
Layout Management: pack()
 pack() method rearranges components such that any unused space is not shown

 Adjusts the size of the frame to fit the components added to it.
How would you create a complex window like
this?
SOLUTION: COMPOSITE LAYOUT
CREATE PANELS WITHIN PANELS EACH PANEL HAS A DIFFERENT LAYOUT, AND BY COMBINING THE LAYOUTS, MORE
COMPLEX / POWERFUL LAYOUT CAN BE ACHIEVED
Event Handling
 How do GUIs interact with users? How do applications recognize when the user has done something?

 Ans: Event Handling

 The way event handling works is this:

 Any operating system that supports GUIs constantly monitors events such as keystrokes and mouse clicks.

 The operating system reports these events to programs that are running.

 The programs decide what, if anything, they want to do with these events.

 In Java, you control how to handle these events by setting up event source objects and event listener objects.
Event Handling

 An event can be defined as a type of signal to the program that something has
happened.
 The event is generated by external user actions such as mouse movements, mouse
button clicks, and keystrokes, or by the operating system, such as a timer.
 Events are responded to by event listeners.
 Each event-generating object (usually a component) maintains a set of listeners
for each event that it generates.
 To be on the list, a listener object must register itself with the event-generating
object.
 Listeners have event-handling methods that respond to the event.

Event-generating Objects send Events to Listener Objects


Event Handling
 Thus, for an application in order to respond to an event for a particular GUI component, you
must perform several coding steps:
1. Create a class that represents the event handler: declares a class that implements a listener
interface (e.g. ActionListener)

2. Implement an appropriate interface, known as an event-listener interface, in the class from


Step 1.

3. Indicate that an object of the class from Steps 1 and 2 should be notified when the event occurs.
This is known as registering the event handler.

 A user interaction creates an event Common events are clicking a button, typing in a text field,
selecting an item from a menu, closing window and moving the mouse. The event causes a call
to a method called an event handler.
Event Handling

Every component support


component, focus, key, mouse
and mouse-motion listeners.

Fires only events for which


listeners has registered an
interest in.

NOTE: any object that will respond to an event must implement a listener
interface.
Event Handling

 Currently, the views painted by the application frame with its constituent
components are like empty shells with no application processing logic underneath.
Event Handling
 Semantic events express what the user is doing.
 e.g. clicking a button
 Low-level events are those that make semantic events possible.
 e.g. mouse moves, mouse clicks, keyboard strokes etc.
 The 4 semantic event classes in java.awt.event package
 ActionEvent
 (for button clicks, menu selections, ENTER typed in text field, selecting a list item)
 AdjustmentEvent
 (the user adjusted a scroll bar)
 ItemEvent
 (the user made a selection from a set of checkboxes or list items)
 TextEvent
 (the contents of a text field or text area were changed)
Event Handling
 The 7 low-level event classes in java.awt.event package
 ComponentEvent
 (the component was resized, moved, shown, or hidden)
 KeyEvent
 (key was pressed or released)
 MouseEvent
 (the mouse button was pressed, released, moved, or dragged)
 MouseWheelEvent
 (the mouse wheel was rotated)
 FocusEvent
 (a component got focus or lost focus)
 WindowEvent
 (the window state changed)
 ContainerEvent
 (a component has been added or removed)
Event Handling
 User actions like clicking a button are modelled by an ActionEvent, and sent to
an ActionListener.

 Window actions like clicking a close or minimize box are WindowEvents, sent
to WindowListeners.

 Mouse actions like pressing the mouse is modelled in a MouseEvent, and is sent
to a MouseListener.

 Mouse movement is modelled in a MouseEvent, and is sent to a


MouseMotionListener.

 Key presses are modelled in a KeyEvent, and is sent to a KeyListener.


Event Handling: Diagram

 To be able to handle events in Java we need 3 things:


1. Event sources: is the component with which user interacts
2. Event objects: is created and contains information about the event that happened
3. Event listeners: is notified when an event happens
Event Handling: Event Sources
 Event sources are components that can recognize user action: menus,
buttons, text fields etc.

 Can be determined using method getSource()

 Event source reports on events and notifies all its listeners

 An event source can have multiple event listeners registered on it.

An Event object’s getSource() method returns a reference to the Component object that generated
the event.
Event Handling: Event Sources
 A source must register listeners
 Each of the event has its own registration method:
 Syntax: <Source> . add<Type>Listener (handler);
 Type is the name of event
 Handler is reference to the event listener
 Example:
 addKeyListener()
 addMouseMotionListener()
 A source also provides a method to ‘unregister’ the listeners.
 public void remove<type>Listener(handler);
Event Handling: Event Objects
 Objects that represent a user action (e.g. mouse click) – contain detailed
information about the event.

 When an event happens an event source sends an event object to its event
listeners

 EventObject is the superclass


 ActionEvent, MouseEvent, etc. are the subclasses that we use

 We are not going into details of EventObjects – we will need them only as
arguments to the method event performer in event listeners.
Event Handling: Event Listeners
 Event listeners are objects that respond when an event occurs; or an object that wants
to be notified when an event has occured on a component.
 Any object , whose class implements the XxxxListener interface, can be an event listener; The
common interface that all event listener interfaces must extend is EventListener.

 ActionListener extends EventListener and is in the java.awt.event package, which is where all the AWT event classes
and listener interfaces are defined.

 If the event listener has been added to an event source, the listener will be called when an
event occurs on that source.
Event Handling: Event Listeners
 The javax.swing.event package contains the event classes and listener
interfaces unique to Swing.
 The AWT components only generate AWT events, while Swing components
generate both AWT and Swing events.
 For example, a Swing JButton is the source of java.awt.event.ActionEvent (an
AWT event class) and a javax.swing.event.ChangeEvent (a Swing event class).
Three Required Parts
 Every event handler requires three pieces of code:

1. Declaration of the event handler(listener) class that implements a listener interface or extends a class that

implements a listener interface

public class MyClass implements XxxListener {

2. Registration of an instance of the event handler class as a listener

someComponent.addXxxListener(instanceOfMyClass);

3. Providing code that implements the methods in the listener interface with in the event handler class

public void EventPerformerMethod (XxxEvent e)

//code that reacts to the action...


Listener Classes Usage
 If the listener class is different class, we have to do
 ListenerClass lc = new ListenerClass();

 JButton btnTest = new JButton(“Test”);

 btnTest.addActionListener(lc);

 if the Listener class is the class that contains the source object, then the reference
to the Listener object will be ‘this’

btnTest.addActionListener(this);

 The Listener must implement the appropriate Listener interface and define
methods to receive and process notifications
Button(Action Listener)
 To Listen and process the ActionEvent generated by the source button, the Listener class must
implement ActionListener interface

 The method to be implemented is actionPerformed.

class ListenerClass implements ActionListener{

public void actionPerformed (ActionEvent ae){

ae.getSource(); //returns source object reference

ae.getActionCommand(); //returns caption of the source(String)

}
Text Field(Action Listener)
Text Field(Action Listener)
Item Event
(JCheckBox, JRadioButton, JComboBox)
 Occurred by sources JCheckBox, JRadioButton, JComboBox.
 JCheckBox and JRadioButton have two state SELECTED and
DESELECTED
 Methods
(event object).getSource();//returns the source object
(event object).getStateChange() = = ItemEvent.SELECTED or
ItemEvent.DESELECTED
 Listener interface that the Listener class must implement is ItemListener
 Method that the Listener class should implement is
public void itemStateChange(ItemEvent ie);
JCheckBox(Action Listener)
• You may not want to be
alerted every time the user
selects or deselects a
checkbox.

• A more common use is to


check the state of the button
when the user clicks a button
signifying that he/she is done
and ready to advance.
JCheckBox(Action Listener)
JCheckBox(Item Listener)
JRadioButton (Action Listener)
JRadioButton (Action Listener)
JRadioButton (Item Listener)
JComboBox(Action Listener)
 Notice the use of
the Set.
 If we were to get
the combo box
choices from a file,
we could prohibit
duplicates by using
a Set.

notice use of collection


JComboBox(Item Listener)
List (List Selection Listener)
Mouse Event Handling

 MouseEvent: There are two types of Listener interfaces


 MouseListener: There are five methods to be implemented
 public void mouseClicked(MouseEvent me);
 public void mouseEntered(MouseEvent me);
 public void mouseExisted(MouseEvent me);
 public void mouseReleased(MouseEvent me);
 public void mousePressed(MouseEvent me);
 MouseMotionListener:
 public void mouseMoved(MouseEvent me);
 public void mouseDragged(MouseEvent me);
Mouse Event Handling

 Each of the mouse event handling methods takes a MouseEvent object as its
argument.
 A MouseEvent object contains information about the mouse event that occurred,
including the x- and y-coordinates of the location where the event occurred.
 Class MouseEvent inherits several methods from class
InputEvent that can distinguish between mouse buttons.
 isMetaDown() This method returns true when the user clicks the right mouse button
on a mouse with two or three buttons. To simulate a rightmouse-button click on a one-
button mouse, the user can press.
 isAltDown() This method returns true when the user clicks the middle mouse button
on a mouse with three buttons. To simulate a middlemouse-button click on a one- or
two-button mouse, the user can press the Alt key on the keyboard and click the mouse
button.
Mouse Event Handling

 the main thing you want to know about a MouseEvent is the location; that is,
where the mouse was clicked.
 You can either request the x and y locations separately, or together as a
java.awt.Point object.
public int getX()
public int getY()
public Point getPoint()
Example

public void mousePressed(MouseEvent event) {


Point p = event.getPoint();
Object source = event.getSource();
if (source == this.panel && p.getX() < 10) {
JOptionPane.showMessageDialog(null,
"You clicked the left side of myPanel!");
}
}
Example: Dots

import java.applet.*; public void mouseEntered(MouseEvent evt) {}


import java.awt.*;
public void mouseExited(MouseEvent evt) {}
import java.awt.event.*;
import java.util.*; public void paint(Graphics g) {
public class Dots extends Applet implements MouseListener { g.setColor(Color.red);
private Vector theDots = new Vector();
Enumeration e = theDots.elements();
public void init() {
this.addMouseListener(this); while (e.hasMoreElements()) {
} Point p = (Point)
public void mouseClicked(MouseEvent evt) {
e.nextElement();
theDots.addElement(evt.getPoint());
this.repaint(); g.drawOval(p.x, p.y, 5, 5);
} } }}
public void mousePressed(MouseEvent evt) {}
public void mouseReleased(MouseEvent evt) {}
Mouse and Mouse Motion Listeners

 Generally you respond to mouse events directed at your component, by


registering a MouseListener object with the component.
public interface MouseListener extends EventListener
 For reasons of efficiency, the MouseListener interface only declares five methods:

public abstract void mouseClicked(MouseEvent evt)


public abstract void mousePressed(MouseEvent evt)
public abstract void mouseReleased(MouseEvent evt)
public abstract void mouseEntered(MouseEvent evt)
public abstract void mouseExited(MouseEvent evt)
Mouse Motion Listener

 A mouse listener does not respond to mouse dragged or mouse moved events
because these are too common.
 mouse moved and mouse dragged events are responded to by the
MouseMotionListener interface.
public interface MouseMotionListener extends EventListener
 The MouseMotionListener interface declares these two methods that are missing
from MouseListener:
public abstract void mouseDragged(MouseEvent evt)
public abstract void mouseMoved(MouseEvent evt)
Example

public void mouseMoved(MouseEvent event) {


Point p = event.getPoint();
double x = event.getX();
double y = event.getY();
System.out.println("Mouse is at " + p);
System.out.println("x is " + x);
System.out.println("y is " + y);
}
myPanel.addMouseMotionListener(this);
Example
Window Event

 To capture window events (such as when the user closes a window), you must have an object that
implements the WindowListener interface. The JFrame is the source of a WindowEvent.
e.g. WindowListener listener = …;
frame.addWindowListener(listener);
 The WindowListener interface has seven distinct events that can happen. That means you must
override seven abstract methods.
 An object that implements the WindowListener interfact must override these methods:
 void windowOpened(WindowEvent e);
 void windowClosing(WindowEvent e);
 void windowClosed(WindowEvent e);
 void windowIconified(WindowEvent e);
 void windowDeiconified(WindowEvent e);
 void windowActivated(WindowEvent e);
 void windowDeactivated(WindowEvent e);
Example
Keyboard Event Handling

 A class that implements KeyListener must provide definitions for methods


keyPressed, key-Released and keyTyped, each of which receives a KeyEvent as
its argument.
 Class KeyEvent is a subclass of InputEvent. Method keyPressed is called in
response to pressing any key.
 Method keyTyped is called in response to pressing any key that is not an action
key (e.g., an arrow key, Home, End, Page Up, Page Down, a function key, Num
Lock, Print Screen, Scroll Lock, Caps Lock and Pause).
 Method keyReleased is called when the key is released after any keyPressed or
keyTyped event.
Keyboard Event Handling

 A java.awt.event.KeyEvent is sent to a component when a key is pressed while


the component has the focus.
 There are three types of key events, each represented by an integer constant:
– KeyEvent.KEY_PRESSED: A key was pressed
– KeyEvent.KEY_RELEASED: A key was released
– KeyEvent.KEY_TYPED: A key press followed by a key release.
 The main thing you want to know about a KeyEvent is what key was pressed. You
get this with the getKeyChar() method.
public char getKeyChar()
This returns the Unicode character corresponding to the pressed key.
Keyboard Event Handling

 A KEY_PRESSED or KEY_RELEASED event doesn't just have a character. It


also has a key code.
 KEY_TYPED events do not have key codes. More precisely the key code is
undefined.
 If you're concerned about the key that was pressed, rather than the character that
was typed, you'll ask the key event for its key code rather than its key char.
 You get the code for a KeyEvent by calling getKeyCode():
public int getKeyCode()
Keyboard Event Handling

 You can convert this into a localized string such as "END", "F4" or "Q" by
passing it to the static method, KeyEvent.getKeyText():
public static String getKeyText(int keyCode)
 Generally you respond to key events directed at your component, by registering a
KeyListener object with the component.
 The KeyListener interface defines the following methods, one for each type of
KeyEvent.
public abstract void keyTyped(KeyEvent evt)
public abstract void keyPressed(KeyEvent evt)
public abstract void keyReleased(KeyEvent evt)
Key Listener: Example
Key Codes

 The KeyEvent class defines a little more than one hundred virtual key codes that
map to different, common, keyboard keys.
 KeyEvent.VK_0 through KeyEvent.VK_9 are the same as ASCII '0' through '9'
(0x30 - 0x39)
 KeyEvent.VK_A through KeyEvent.VK_Z are the same as ASCII 'A' through 'Z';
Funky Key Codes

The remaining keys are the interesting ones: KeyEvent.VK_CONTROL,


KeyEvent.VK_ACCEPT, KeyEvent.VK_CONVERT,
KeyEvent.VK_ADD, KeyEvent.VK_ALT, KeyEvent.VK_DECIMAL,
KeyEvent.VK_BACK_QUOTE, KeyEvent.VK_DELETE,
KeyEvent.VK_BACK_SLASH, KeyEvent.VK_DIVIDE,
KeyEvent.VK_BACK_SPACE, KeyEvent.VK_DOWN,
KeyEvent.VK_CANCEL,
KeyEvent.VK_END,
KeyEvent.VK_CAPS_LOCK,
KeyEvent.VK_CLEAR, KeyEvent.VK_ENTER,
KeyEvent.VK_EQUALS,
KeyEvent.VK_CLOSE_BRACKET,
KeyEvent.VK_COMMA,
KeyEvent.VK_ESCAPE,
KeyEvent.VK_F1,
KeyEvent.VK_F2,
KeyEvent.VK_F3
Funky Key Codes

KeyEvent.VK_F4, KeyEvent.VK_KANJI,
KeyEvent.VK_F5, KeyEvent.VK_LEFT,
KeyEvent.VK_F6, KeyEvent.VK_META,
KeyEvent.VK_F7, KeyEvent.VK_MODECHANGE,
KeyEvent.VK_MULTIPLY,
KeyEvent.VK_F8,
KeyEvent.VK_NONCONVERT,
KeyEvent.VK_F9, KeyEvent.VK_NUM_LOCK,
KeyEvent.VK_F10, KeyEvent.VK_F11, KeyEvent.VK_NUMPAD0,
KeyEvent.VK_F12, KeyEvent.VK_NUMPAD1,
KeyEvent.VK_FINAL, KeyEvent.VK_NUMPAD2,
KeyEvent.VK_HELP, KeyEvent.VK_NUMPAD3
KeyEvent.VK_HOME,
KeyEvent.VK_INSERT,
KeyEvent.VK_KANA,
Funky Key Codes

KeyEvent.VK_NUMPAD4, KeyEvent.VK_RIGHT,
KeyEvent.VK_NUMPAD5, KeyEvent.VK_SCROLL_LOCK,
KeyEvent.VK_NUMPAD6, KeyEvent.VK_SEMICOLON,
KeyEvent.VK_NUMPAD7, KeyEvent.VK_SEPARATER,
KeyEvent.VK_NUMPAD8,
KeyEvent.VK_SHIFT,
KeyEvent.VK_NUMPAD9,
KeyEvent.VK_OPEN_BRACKET, KeyEvent.VK_SLASH,
KeyEvent.VK_PAGE_DOWN, KeyEvent.VK_SPACE,
KeyEvent.VK_PAGE_UP, KeyEvent.VK_SUBTRACT,
KeyEvent.VK_PAUSE, KeyEvent.VK_TAB,
KeyEvent.VK_PERIOD, KeyEvent.VK_UNDEFINED,
KeyEvent.VK_PRINTSCREEN, KeyEvent.VK_UP
KeyEvent.VK_QUOTE,
Modifier Keys

 The primary feature InputEvent adds the ability to test for additional conditions
on the event such as whether the ALT key was pressed at the same time as another
key, or whether the option key was held while the mouse was dragged.
 The following four methods tell you whether or not the specified key was pressed
when this event was sent.
public boolean isShiftDown()
public boolean isControlDown()
public boolean isAltDown()
public boolean isMetaDown()

 All may be invoked on either MouseEvent objects or KeyEvent objects.


Modifier Keys

 There is also a getWhen() method which returns the time the event occurred. This
is given as the number of milliseconds since midnight, January 1, 1970,
Greenwich Mean Time.
public long getWhen()
 The java.util.Date and java.util.Calendar classes have methods you can use to
convert this to a date and time.
 However, most of the time you'll only be concerned with differences in the time
between one event and another.
Mouse Button Modifiers

 An InputEvent's modifiers are stored as an int value. Each bit in the int is a flag
corresponding to a particular modifier.
 The corresponding values for these flags are given in the InputEvent class:
 InputEvent.SHIFT_MASK
 InputEvent.CTRL_MASK
 InputEvent.ALT_MASK
 You can retrieve the modifiers for an event with the getModifiers() method:
public int getModifiers()
 Use the bitwise & operator to test whether a particular flag is set.
if (evt.getModifiers() & InputEvent.SHIFT_MASK != 0) {
System.out.println(“SHIFT was pressed");
}
Adapter Classes

 Many of the event-listener interfaces provide multiple methods; MouseListener


and MouseMotionListener are examples. It is not always desirable to define every
method in an event-listener interface.
 For example, a program may only need the mouse-Clicked handler from interface
MouseListener or the mouseDragged handler from MouseMotionListener.
 An adapter class implements an interface and provides a default implementation
(with an empty method body) of every method in the interface.
Adapter Classes

 To make it easier for programmers, the designers of Java supplied adapter classes.
 Each AWT listener interface with more than one method comes with a companion
adapter class.
 These adapter classes implement all the methods in the interface but does nothing with
them.
 This means that the adapter classes satisfy all the technical requirements for
implementing the listener interface.
 You can then just extend your class from these adapter classes if you don’t need to
extend it from anything else.
 The programmer can extend the adapter class to inherit the default
implementation of every method, then override the method(s) needed for event
handling.
Adapter Classes

 The adapter class for the WindowListener interface is WindowAdapter. You can use it like
this:
 class Terminator extends WindowAdapter {…}
 Creating a listener class that extends the WindowAdapter is even easier than that. There is
no need to give a name to the listener object.
 frame.addWindowListener(new Terminator());
 You can go even further by using an anonymous inner class:
 frame.addWindowListener(new
WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0)
}
});
 Have you observed the code?.
Adapter Classes

import java.awt.*; Without extending the MouseAdapter class, I would have had to
write the same class like this:
import java.awt.event.*;
import java.awt.*;
public class MouseBeeper extends MouseAdapter {
import java.awt.event.*;
public void mouseClicked(MouseEvent evt) {
public class MouseBeeper implements MouseListener {
Toolkit.getDefaultToolkit().beep();
public void mouseClicked(MouseEvent evt) {
}
Toolkit.getDefaultToolkit().beep();
}
}

public void mousePressed(MouseEvent evt) {}

public void mouseReleased(MouseEvent evt) {}

public void mouseEntered(MouseEvent evt) {}

public void mouseExited(MouseEvent evt) {} }

Adapter classes are a minor convenience.

You do not need to use the adapter classes if you don't want to.
Menu

 A menu provides a space-saving way to let the user choose one of several options.
 Menus are unique in that, by convention, they aren't placed with the other components
in the UI.
 Instead, a menu usually appears either in a menu bar or as a popup menu.
 Menus are composed of three hierarchical pieces.
 MenuBar, Menu and MenuItem
 The menu bar contains the various menus.
 Each menu bar contains one or more menus.
 Each menu contains one or more menu items.
 The menu items are the individual actions such as Open, Print, Cut or Copy.
 They are not shown except when the menu is active.
 No more than one menu will be active at a time.
Menu

 Java provides several classes:


 JMenuBar, JMenu, JMenuItem, JCheckBoxMenuItem, and JRadioButtonMenuItem —
to implement menus in a frame
 The JMenuBar Class
 holds menus
 the menu bar can only be added to a frame
 For example:
 JFrame f = new JFrame();
 f.setSize(300, 200);
 f.setVisible(true);
 JMenuBar mb = new JMenuBar(); f.setJMenuBar(mb);
Menu

1. create menu bar object.


JMenuBar mbobj = new JMenuBar();
2. set Menubar to the frame
frameobj.setJMenuBar(mbobj);
3. create Possible Menus.
JMenu mnobj = new JMenu(“String”)

4. Add menu to the menu bar.


mbobj.add(mnobj);

5. create Possible Menu item.


JMenuItem miobj = new JMenuItem(“String”);

6. Add menu item to the Menus


mnobj.add(miobj);
Exercise: Open File Chooser With Menu Item (Action Listener)
Popup Menu

 Pop-up menus are an increasingly popular user-interface feature.


 These menus are not attached to a menu bar; instead, they are free-floating menus that associate
themselves with an underlying component.
 The PopupMenu class, is activated when the user holds the right mouse button or otherwise indicates
that they want to pop up a menu.
 Typically this is used for context sensitive menus.
 java.awt.PopupMenu is a subclass of of java.awt.Menu.
 Items are added to it with the add(MenuItem mi) method, and user selections are responded to by
installing an ActionListener on the MenuItem.
Color Setting

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

Colors are made of red, green, and blue components, each of which is represented by
a byte value that describes its intensity, ranging from 0 (darkest shade) to 255
(lightest shade).

This is known as the RGB model.


Color c = new Color(r, g, b);
r, g, and b specify a color by its red, green, and blue components.

Example:
Color c = new Color(228, 100, 255);
Color Setting: Standard Colors

 Thirteen standard colors (black, blue, cyan, darkGray, gray, green, lightGray,
magenta, orange, pink, red, white, yellow) are defined as constants in java.awt.Color.
 The standard color names are constants, but they are named as variables with
lowercase for the first word and uppercase for the first letters of subsequent words.
 Thus the color names violate the Java naming convention. Since JDK 1.4, you can
also use the new constants: BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN,
LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, and YELLOW.
Color Setting

 You can use the following methods to set the component’s background and foreground colors
(There are thirteen standard color names):
setBackground(Color c)
setForeground(Color c)
 Example:
jbt.setBackground(Color.yellow);
jbt.setForeground(Color.red);
 If for some reason, the selections built into the Color object do not fit your needs, you can create
your own color using one of over 16 million different combinations.
 Color myColor = new Color(redValue, greenValue, blueValue);
Color Chooser

 JColorChooser() It is used to create a color chooser panel with white color


initially.
 JColorChooser(color initialcolor) It is used to create a color chooser panel with
the specified color initially.
 void addChooserPanel(AbstractColorChooserPanel panel) It is used to add a color
chooser panel to the color chooser.
 static Color showDialog(Component c, String title, Color initialColor) It is used to
show the color chooser dialog box.
Color Chooser
Font Setting

Font myFont = new Font(name, style, size);


Example:
Font myFont = new Font("SansSerif ", Font.BOLD, 16);
Font myFont = new Font("Serif", Font.BOLD+Font.ITALIC, 12);

JButton jbtOK = new JButton("OK“);


jbtOK.setFont(myFont);

Font Names Font Style


Standard font names that are Font.PLAIN (0), Font.BOLD (1),
supported in all platforms are: Font.ITALIC (2), and Font.BOLD
SansSerif, Serif, Monospaced, + Font.ITALIC (3)
Dialog, or DialogInput.
Font Setting: Finding Available Font
Names
GraphicsEnvironment e =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = e.getAvailableFontFamilyNames();
for (int i = 0; i < fontnames.length; i++)
System.out.println(fontnames[i]);

Font sansbold14 = new Font("SansSerif", Font.BOLD, 14)


Font.PLAIN
Font.BOLD
Font.ITALIC
Font.BOLD + Font.ITALIC
Border

 You can set a border on any object of the JComponent class.


 import javax.swing.border.*;
 Swing has 8 types of borders: bevel, soft bevel, empty, etched, line, matte, titled, and compound.
 Titled border
new TitledBorder(String title).
JPanel panel = new JPanel();
panel.setBorder(new TitleBorder(“My Panel”));
 Line border
new LineBorder(Color color, int width),
 where width specifies the thickness of the line. For example, the following code displays a titled
border on a panel:
 Bevel Border (setBorder(new BevelBorder(BevelBorder.LOWERED));)
 Etched Border
Mnemonics

 Mnemonic: menu hotkey assigned to a button or other graphical component


 Usually visible as an underlined key, activated by pressing Ctrl+key (buttons) or
Alt+key (menus)
 usage: call setMnemonic(char) method
 Example: myQuitButton.setMnemonic(‘Q');
 Menu items also have constructor that takes mnemonic
 JMenuItem myNewItem = new JMenuItem("New");
 myNewItem.setMnemonic('N');
Look and Feel

 f=new Jframe();
 UIManager.setLookAndFeel("javax.swing
.plaf.metal.MetalLookAndFeel");
 UIManager.setLookAndFeel("com.sun.jav
a.swing.plaf.windows.WindowsLookAnd
Feel");
 UIManager.setLookAndFeel("javax.swing
.plaf.nimbus.NimbusLookAndFeel");
 UIManager.setLookAndFeel("com.sun.jav
a.swing.plaf.motif.MotifLookAndFeel");
Set Frame Icon

 Create a new ImageIcon object like this:


 ImageIcon img = new ImageIcon(getClass().getResource( pathToFileOnDisk));
 Then set it to your JFrame with setIconImage():
 myFrame.setIconImage(img.getImage());
Beep and Print Job

 Beep
 Toolkit.getDefaultToolkit().beep();
 Get Print Job
 Toolkit.getDefaultToolkit() .getPrintJob(null, null, new Properties());
Swing is HUGE! You must explore it
further…
} CHAPTER 3

You might also like