0% found this document useful (0 votes)
10 views139 pages

��نسخة chapter 2�

This document provides an overview of graphical interfaces in Java, focusing on two main libraries: AWT and Swing. It discusses the structure of graphical components, including containers like JFrame and JPanel, as well as layout managers for organizing components. Additionally, it covers how to create and manage graphical windows and components in Java applications.

Uploaded by

Mostafa 3tta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views139 pages

��نسخة chapter 2�

This document provides an overview of graphical interfaces in Java, focusing on two main libraries: AWT and Swing. It discusses the structure of graphical components, including containers like JFrame and JPanel, as well as layout managers for organizing components. Additionally, it covers how to create and manage graphical windows and components in Java applications.

Uploaded by

Mostafa 3tta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Visual Programming

Dr Hedia ZARDI
[email protected]

1
Chapter 2:
Graphical interfaces

Dr Hedia ZARDI
[email protected]

2
Outline of Chapter 2
— Graphical interfaces
— AWT
— SWING
— Create an interface
— The window JFrame
— The panel JPanel
— Adding components
— Component distributions
— Event management
— Adapters

3
Graphical interfaces
— A graphical interface (windows, buttons, menus…) requires a lot of
components and lines of code.

— It is interesting to separate the graphical interface part from the rest of


the program. The object approach is well suited.

— Java offers 2 systems for creating graphical interfaces:

— the oldest is called AWT (TObstract Window Toolkitor "abstract


windowing library"); java.awt package

— the most recent (since Java 2) is called Swing. It is an improvement of AWT;


packagejavax.swing.

— Swing is a set of classes used to create objects representing graphic


components.
4
AWT
— AWT: Abstract Window Toolkit
— Package: java.awt

— Uses components heavy using a lot of system resources

— Linked directly to the possibilities of the graphical user interface of the


local platform.

— Least Common Denominator


àIf not natively available on one of the platforms Java, then not available on all
platforms Java

— Simple Component Set

— Different display depending on the platform


5
Containers and components
— A graphical interface in Java is an assembly containers
(Container) and components (Component).

— A component is a "visible" part of the Java user


interface.
— It is a subclass of the abstract class java.awt.Component.
— Example: buttons, text or drawing areas, etc.

— A container is a space in which you can position


several components.
— Class subclass java.awt.Container.
— The Container class is itself a subclass of the Component class
— Example: windows, applets, etc.
6
Inheritance hierarchy of the main
elements of graphical interfaces in Java
Object
(from la ng)
Button
Graphic components are placed in
Canvas Component Containers

Checkbox

Container
Choice

Label
Panel Window

Scrollbar List

Dialog Frame
Applet
TextComponent
(from applet)

FileDialog
TextArea TextField

7
Containers and components
• The two most common containers are the Frame and the Panel.

• a Frame represents a high-level window with a title, border, and


resizing angles.
¨ Most applications use at least one Frame as a starting point for their
GUI.
• a Panel does not have a clean appearance and cannot be used as a
stand-alone window.
¨ Panels are created and added to other parts in the same way as
components such as buttons.
¨ Panels can then redefine their own layout to contain other
components themselves.
8
Swing
— The library Swing is a new library of graphics components
for Java.
— Swing is integrated with Java 1.2. (Java 2)
— Swing can be downloaded separately for use with earlier versions of
Java (1.1.5+)

— This library is added to the one that was used until then
(AWT) for compatibility reasons.
— Swing, however, overlaps in many cases with AWT.
— Sun's ambition is that, gradually, the developers realize all their
interfaces with Swing and drop the old ones. API graphics.

9
Swing
• a heavy graphics component (heavyweight GUI component) relies on
the local window manager, that of the machine on which the
program is running.

Ø AWT only has heavy components.

10
Swing
• Example :
¨ A button of type java.awt.Button integrated in a Java application on
the Unix platform is represented by a real Motif button (called its
peer - peer in English).

¨ Java communicates with this Motif button using the Java Native
Interface. This communication incurs a cost.

¨ This is why this button is called a heavy component.

11
Swing
• a lightweight graphics component (in English, lightweight GUI
component) is a graphical component independent of the local
window manager.
¨ A lightweight component looks like a local window manager
component but is not: a lightweight component emulates local
window manager components.

¨ A light button is a rectangle drawn on a canvas that contains a label


and responds to mouse events.

¨ All Swing components, excepted JApplet, JDialog, JFrame


and JWindow are lightweight components.
12
Swing package view
— Basic components
— JApplet
— JButton
— JCheckBox
— JRadioButton
— JToggleButton
— JComboBox
— JList
— JSlider
— JTable
— JTree
— JProgessBar
— JSpinner

13
Swing package view
— Menus, Toolbar and Info Bubbles
— JMenuBar
— JMenu
— JMenuItem
— JCheckBoxMenuItem
— JRadioButtonMenuItem
— JPopupMenu
— JToolBar
— JToolTip

14
Swing package view
— Menus, Toolbar and Info Bubbles
— JMenuBar
— JMenu
— JMenuItem
— JCheckBoxMenuItem
— JRadioButtonMenuItem
— JPopupMenu
— JToolBar
— JToolTip

15
Swing package view
— Text components
— JPasswordField
— JTextField
— JTextArea
— JTextPane
— JEditorPane

JTextfield this is for single line


JTextarea on for some text on
text
JEditorPane allows you to edit
several lines
content of different kinds: Text,
HTML, etc

16
Swing package view
— Containers
— JOptionPane
— JDialog
— JTabbedPane
— JSplitPane
— JScrollPane
— JFrame
— JInternalFrame
— JDesktopPane
— JWindow

17
Swing package view
— Containers
— JOptionPane
— JDialog
— JTabbedPane
— JSplitPane
— JScrollPane
— JFrame
— JInternalFrame
— JDesktopPane
— JWindow

18
Create an interface
— The window JFrame

19
The window JFrame
— To create a graphics window, we have, in the package javax.swing, a
standard class named JFrame possessing:

— A constructor without arguments:


— JFrame fen = new JFrame();

— If we limit ourselves to that, nothing will appear on the screen.

— You must request the display of the window by calling one of these two
methods:

— fen.setVisible(true);

— fen.show();

20
The window JFrame
— Other essential functions for creating a window:
— By default, the size of a window is zero. To define the dimensions on the
screen, use the function:

— fen.setSize( l, h);
— h: the height in pixels;
— L: the width in pixels;

— Example:
fen.setSize(300,150);

21
The window JFrame
— Other essential functions for creating a window:
— In general, we will choose to display a specific text in the title bar.

— We then use:
— fen.setTitle(String Message);

— Example:
— fen.setTitle(''My first window'');

22
The window JFrame
— The user can handle this window like any graphics window in
software:
— Resize it
— Move it
— Reduce it to an icon.

— Warning, closing a window of type JFrame born not terminate the


program, but simply make the window invisible (as if calling the
method setVisible (false)).

23
The window JFrame
— For closing the window to end the program, add:
— setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );

— To close the window without terminating the program, add:


— setDefaultCloseOperation ( JFrame.DISPOSE_ON_CLOSE );

— The effect of this instruction is only visible if you have opened more
than one window in your program.

24
The window JFrame
— Creating a custom window class:

— In the previous example, we simply created an object of type JFrame and


we used the functionality present in this class.

— For our program to be of interest, additional functionality must be


associated with it: the window must be able to react to certain events.

— For this, we will need to define our own class derived from JFrame and
create an object of this new type.

25
The window JFrame
— Creating a custom window class:
import javax.swing. *;

public class Window extends JFrame{


public Window()
{
setSize(300,150);
setTitle("My first window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main (String [] args) {


Window premFen = new Window();
premFen. setVisible(true);
}
}

26
The window JFrame
— Reposition and resize a window:

— You can use the function:

— setBounds(px, py, l, h)

— With:

— px and py: the coordinates of the pixel which presents the new position of the
window.

— h and l: the new dimensions of the window.

27
The window JFrame
— Reposition and resize a window:

import javax.swing. *;

public class Window extends JFrame{


public Window()
{
setSize(300,150);
setTitle("My first window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main (String [] args) {


Window premFen = new Window();
premFen. setVisible(true);
premFen.setBounds(250,250,300,200);
}
}

28
The window JFrame
— Reposition and resize a window:
— If we want to position the window in relation to the size of the
screen:

— You must use a tool kit (Toolkit) allowing you to load the dimensions,
icons and all the necessary tools from the Operating System (Java.awt
package).

29
The window JFrame
— Reposition and resize a window:
— Example: import javax.swing. *;
public class Window extends JFrame{
public Window()
{
setTitle("My first window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main (String [] args) {
Window premFen = new Window(); Repositioning and
premFen. setVisible(true); resizing relative to the
Toolkit kit = Toolkit.getDefaultToolkit(); screen
Dimension screenSize = kit.getScreenSize();
int H = screenSize.height; // Height
intW = screenSize.width; //Width
premFen.setBounds(W / 4, H / 4, W / 2, H / 2);
Picture img = kit.getImage("icon.gif"); Changing the window
this.setIconImage(img); icon
}
30 }
The panel JPanel
— He not possible to directly
introduce a component in a window
(JFrame).

— JFrame has a structure complex. It is


formed by a superposition of several
elements, in particular a root, a
content,etc .

— The method getContentPane of style


JFrame provides the reference to this
content of type Container:
— Container c = getContentPane();
Or
— Jpanel c = new JPanel(); c =
(JPanel)getContentPane();
31
The panel Jpanel: Addition of components
— the different components are to be added in the content part with
method add .
— c.add (component);
— c.remove(making up); for deletion.

— But the method add always add the component in the same place
in the container.

— So when you want to add several components to the panel, only


the last component appears .

32
The panel Jpanel: Addition of components
class Window extends JFrame
{
private JButton button1, button2;
private JLabel label1, label2;
private JTextField text1, text2;

public Window()
{
setSize(400,300);
setTitle("A window with components");

// create components
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
label1 = new JLabel("Label 1");
label2 = new JLabel("Label 2");
text1 = new JTextField("Text box 1");
text2 = new JTextField("Text box 2");
33
The panel Jpanel: Addition of components
JPanel c = (JPanel)getContentPane();

// add the components


c.add (button1);
c.add (label1);
c.add (text1);
c.add (button2);
c.add (label2);
c.add (text2);

} // end of constructor of the class Window

public static void main (String args[])


{
Window premFen = new Window ();
premFen.show();
}

} // end of the class Window


34
The panel Jpanel: Addition of components

Only the last


Must thereforecomponent appeared
divide the frame.

35
Absolute positioning
— To place components at a specific location, we must indicate
that we do not use LayoutManager.
ContainerObject.setLayout(null);

— And we indicate the coordinates and size of each component


Making up.setBounds(x, y, width, high);

— x is the displacement relative to the left of the container


— y is the displacement relative to the top of the container

36
Presentation managers
— Each container is associated with a presentation manager (GP) or layout
manager (layout manager)

— The GP controls the location and size of components each time they are
displayed.

— The rearrangement of components in a container takes place during:

— the modification of its size,


— changing the size or moving one of the components.
— adding, showing, removing or hiding a component.

37
Presentation managers
— Any container has a default GP.

— Any instance of Container references an instance of the class


LayoutManager of the package java.awt.
— It is possible to change it using the method setLayout().

— All the GPs are classes of java.awt who inherit from


LayoutManager.

38
Presentation managers
— To position a component, we have several predefined positions.
These positions that are offered by Java are:
— BorderLayout
— BoxLayout
— CardLayout
— FlowLayout
— GridBagLayout
— GridLayout
— The GPs default are:
— the BorderLayout for JFrame and his descendants
— the FlowLayout for JPanel and his descendants (JApplet, etc.)

39
Presentation managers
BoxLayout BorderLayout

GridLayout GridBagLayout

40
FlowLayout
— FlowLayout organizes components in rows, left to right, then top to
bottom, using the preferred size (preferredSize) of each component.

— FlowLayout places as many components as possible online, before


starting over on a new row.

— Alignment in a FlowLayout can be on the left (FlowLayout.LEFT),


To law (FlowLayout.RIGHT) Where centered (FlowLayout.CENTER)

— by default, components are centered within the area allocated to them.


— a horizontal or vertical spacing between two components is defined using
the methods setHgap() and setVgap().
41
FlowLayout
— the FlowLayout actually and effectively hides the components that
do not fit in the frame.

— the FlowLayout is only of interest when there are few


components in the container.

— Example:
— JPanel p = (JPanel) this.getContentPane();
p.setLayout(new FlowLayout(FlowLayout.LEFT));

42
FlowLayout
— Calling the pack () method for a window (JFrame) asks him to
calculate his height (preferredSize), according to the
components it contains, then to resize itself by adopting this
size. This generally has the effect of making it as small as possible
while respecting thepreferredSize of the components contained.

— The pack method automatically gives the window a minimum


size while preserving the appearance of all its components and
subcontainers.

43
BorderLayout
— BorderLayout divides its workspace into five zones geographic :
NORTH, SOUTH, EAST, WEST and CENTER.
— The components are added by name to these zones (only one
component per zone).
— Example:
— add (new Button ("The button North ! "),
BorderLayout.NORTH);
— If one of the border areas contains nothing, its size is 0.

44
BorderLayout
— Disposal strategy of BorderLayout

— Components in NORTH and SOUTH adopt their preferred height


and span the full width of the container.

— The components located in EAST and WEST adopt their preferred


width and extend vertically over the remaining space between the
NORTH and SOUTH zones.

— The component located in CENTER fills all the remaining space.

45
BorderLayout

— BorderLayout is a useful layout manager for large containers a


user interface.

— By nesting a panel in each area of the container BorderLayout,


then filling in each of these panels with other panels of various
layouts, we can create rich user interfaces.

46
GridLayout
— GridLayout places the components on a grid of cells in rows and
columns.

— It expands each component so that it fills the available space in the cell.

— All cells are exactly the same size and the grid is uniform.

— Following a resizing of the container, GridLayout changes the size of


the cells so that they are as large as possible given the space available in
the container.

— Construction of a GridLayout : new GridLayout(3.2);

47
GridLayout
— The number of rows or columns can be zero, but not both. At least
one value must be specified so that theGridLayout can calculate the
second.

— GridLayout is used to design a container where all components must


be the same size, for example a numeric keypad or toolbar.

48
GridLayout
— The number of pixels between cells is specified using the methods
setHgap() and setVgap(). Space horizontal and vertical space are zero
by default.

— These two methods belong to the class Gridlayout;

49
Exercise
— Write a JAVA program that calculates the average of 2 integers entered as
parameters of the class, and display it on a window.

50
Exercise

window2 package;
import javax.swing. *;
import java.awt. *;
public class Window2 extends JFrame{

private JLabel l1, l2;

public Window2 (String t, String a, String b)


{
super (t);
setLocation(500,270);
setSize(200.70);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

l1 = new JLabel("The mean is =");

51
Exercise
JPanel p = (JPanel) this.getContentPane();
FlowLayout fl= new FlowLayout(FlowLayout.LEFT);
p.setLayout(fl);

double x = Double.parseDouble(a); ç
double y = Double.parseDouble(b);
Double res= new Double ((x + y) / 2);
l2 = new JLabel(res.toString());
String s1 = "the average of" + a + "and" + b;

l2.setToolTipText(s1);
l2.setForeground(Color.red);

p.setBackground(Color.WHITE);

p.add (11, BorderLayout.CENTER);


p.add (12, BorderLayout.NORTH);
}
52
Exercise

public static void main (String [] args) {


Window2 f = new Window2 ("Window 2 ", args[0],args[1]);

f.show();
}
}

53
Event management
— When the user performs an action at the level of the graphical
interface (mouse click, selection of an item, keystroke on the
keyboard, etc), then an event is issued.
— An event is the instance of a class XXXEvent from the
java.awt.event package.

— Example:
— Following a mouse click in a window, it sends an event of type
MouseEvent.

— A button that receives a mouse click emits a class instance event


ActionEvent.

54
Event management
— The component emitting the event is the source of the event. It
transmits this event to one or more other objects, playing the role
ofearphone (Listener).

— Each component SWING is designed to be the source of one or more


particular types of events.

— To process an event of type XXXEvent, a listener must implement the


interface XXXListener

— Any listener of a component must register with this component using the
method addXXXListener().

— A component can be its own listener.


55
Event management

— ActionEvent — ActionListner
— JButton,
— MouseEvent — MouseListner
— JTextFiel
— ... — ...
— ...
56
Event management

57
Event management
— Example1:
import java.awt. *;
import java.awt.event. *;
import javax.swing. *;
public class Window6 extends JFrame
implements ActionListener{
private JButton b;
private JTextField t = new JTextField();
public Window6 () { Window6 is a listener for b. It must
therefore implementActionListener
JPanel c =
(JPanel)this.getContentPane();
c.setLayout(new BorderLayout());
b = new JButton ("OK"); Window6 (this) registers as a
c.add (b, BorderLayout.SOUTH); listener of b.
c.add (t, BorderLayout.NORTH);
58
b.addActionListener(this); }
Event management
— Example1:
import java.awt. *; public void actionPerformed (ActionEvent e)
import java.awt.event. *; {
import javax.swing. *; t.setText("Button pressed");
public class Window6 extends JFrame }
public static void main (String args [])
implements ActionListener{
{
private JButton b; Window6 f = new Window6 ();
private JTextField t = new JTextField(); f.pack ();
public Window6 () { f.setVisible(true);
JPanel c = (JPanel)this.getContentPane();}
c.setLayout(new BorderLayout()); }
b = new JButton ("OK");
c.add (b, BorderLayout.SOUTH);
c.add (t, BorderLayout.NORTH); a ActionListener must implement
b.addActionListener(this); } actionPerformed()

59
Event management
— Example 2: Using inner classes

— It's about a second solution to manage events.

— We create inner classes whose instances will only be used to


listen to events.

— There is thus one class per component dedicated to the


management of events that this component can generate.

60
Event management
package window;
import javax.swing. *;
import java.awt. *; class OkListener implements ActionListener{
import java.awt.event. *;
public class Window extends JFrame { public void actionPerformed(ActionEvent e)
private JButton b1; {
private JTextField t; t.setText("OK button pressed");
public Window () }
{ setLocation(250,250); }
setTitle("Window ");
setSize(200,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
JPanel p = (JPanel)this.getContentPane();
setLayout(new GridLayout(2.1));
b1 = new JButton("OK");
t = new JTextField("Area of Text");
b1.addActionListener(new OkListener());
p.add (t); Creating an
p.add (b1); instance of the
} inner class
61
Event categories
— Several types of events are defined in the package java.awt.event.

— For each category of events, there is an interface that must be


defined by any class wishing to listen to that category of events.

— This interface also requires that one or more methods be defined.

— These methods are called when events in this category occur.

62
Event categories
— ActionListener
— Listen for a button click, carriage return in a text box, etc.
— Requires the implementation of actionPerformed(ActionEvent e)

— TextListener
— Listen to the value change in a text box
— Requires the implementation of textValueChanged(TextEvent e)

— ItemListener
— Listen to the selection of an item in a list
— Requires the implementation of itemStateChanged(ItemEvent e)

— FocusListener
— Listen to the gain or loss of focus by a component.
— Requires the implementation of focusGained(FocusEvent e) and
focusLost(FocusEvent e)
63
Event management
— The event object sent to listeners and passed as parameters of the
corresponding functions can contain parameters of interest for the
application.

— For example, getX() and getY() on a MouseEvent return the


coordinates of the mouse pointer position.

— One of the information that is generally useful for processing an


event is the source of that event. This information is obtained by
calling the methodgetSource() for this event.

— The method Object getSource() is present in all event classes

64
Event management
import java.awt. *; e.getSource() public void actionPerformed(ActionEvent e)
import java.awt.event. *;returns the source {
import javax.swing. *; object of the event if ((JButton) e.getSource() == b1)
public class Window7 extends JFrame
implements ActionListener{ t.setText("OK button pressed");
private JButton b1 = new JButton ("OK"); else
private JButton b2 = new JButton ("To leave"); t.setText("EXIT button
private JTextField t = new JTextField(); hurry");
public Window7 () { }
Container c =this.getContentPane();
c.setLayout(new BorderLayout()); public static void main (String args [])
c.add (b1, BorderLayout.CENTER); {
c.add (b2, BorderLayout.SOUTH); Window7 f = new Window7 ();
c.add (t, BorderLayout.NORTH); f.pack ();
b1.addActionListener(this); f.setVisible(true);
The 2 buttons have the same
b2.addActionListener(this); }
earpiece (the window)
} }
65
Event management
import java.awt. *; public void actionPerformed(ActionEvent e)
import java.awt.event. *; {
import javax.swing. *; if ((JButton) e.getSource() == b1)
public class Window7 extends JFrame
implements ActionListener{ t.setText("OK button pressed");
private JButton b1 = new JButton ("OK"); else
private JButton b2 = new JButton ("To leave"); t.setText("EXIT button
private JTextField t = new JTextField(); hurry");
public Window7 () { }
Container c =this.getContentPane();
c.setLayout(new BorderLayout()); public static void main (String args [])
c.add (b1, BorderLayout.CENTER); {
c.add (b2, BorderLayout.SOUTH); Window7 f = new Window7 ();
c.add (t, BorderLayout.NORTH); f.pack ();
b1.addActionListener(this); f.setVisible(true);
b2.addActionListener(this); }
} }
66
Exercise

— Write a program that displays a window with a button.


When you click on the button, you close the window and
the program stops.

67
Solution
import javax.swing. *;
import java.awt. *;
import java.awt.event. *;
public class Window extends JFrame implements ActionListener{
private JLabel l1;
private JButton b;
public Window ()
{ setLocation(250,250);
setTitle("Window ");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
JPanel p = (JPanel)this.getContentPane();
p.setLayout(new GridLayout(2,1));
b = new JButton("To close");
l1 = new JLabel(" Support on the button to close ");
b.addActionListener(this);
add(l1); public static void main (String [] args) {
add(b); Window fen = new Window();
} fen.setVisible(true);
public void actionPerformed(ActionEvent e) fen.pack();
{ System.exit(0); } }
68 }
Exercise

— Write a program that displays a window on which we see


displayed the number of clicks made on the window.

69
Exercise
— Indication:

— Click on button, move the pointer.

— Interface methods MouseListener

— public void mouseClicked(MouseEvent e)


— public void mouseEntered(MouseEvent e)
— public void mouseExited(MouseEvent e)
— public void mousePressed(MouseEvent e)
— public void mouseReleased(MouseEvent e)

— Events generated by Component

— Recording method addMouseListener


70
Solution
public class Window extends JFrame implements MouseListener{
private JLabel l1, l2;
private static int nb = 0;
public Window ()
{ setLocation(250,250);
setTitle("Counter");
setSize(300.70);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
JPanel p = (JPanel)this.getContentPane();
setLayout(new FlowLayout(FlowLayout.LEFT));

l1 = new JLabel("Number of mouse clicks:");


l2 = new JLabel("0");
add(l1);
add(l2);

addMouseListener(this);
}
71
Solution
public void mouseClicked(MouseEvent e)
{
String s = "";
s + = ++ nb;
l2.setText(s);

// Insert prototypes without defining their bodies.

public void mouseEntered(MouseEvent e) {};


public void mouseExited(MouseEvent e) {};
public void mousePressed(MouseEvent e) {};
public void mouseReleased(MouseEvent e) {};

72
Adapters
— Reminder: a class which implements an interface must redefine
all the methods of the interface

— However, some interfaces Listener have a lot of methods,


which forces you to redefine methods that you have no use for

— To remedy this Java offers Adapter classes for certain interfaces


Listener

73
Adapters
— Instead of implementing the interface, it will suffice to inherit
from the Adapter class.

— In this case the developer redefines only the methods which


interests him.

— Java thus offers a set of Adapter class

— The naming principle is simple: a named class XXXAdapter


corresponds to the earphone interface XXXListener

74
Adapters

— WindowAdapter
— MouseAdapter
— MouseMotionAdapter
— KeyAdapter
— FocusAdapter
— ComponentAdapter
— ContainerAdapter

75
Exercise
— Solution 2: Create an inner class that inherits from the class
MouseAdapter
public class Window extends JFrame{
private JLabel l1, l2;
private static int nb = 0;
public Window ()
{ setLocation(250,250);
setTitle("Counter");
setSize(300.70);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
public class ListenMouse extends MouseAdapter{
JPanel p = (JPanel)this.getContentPane();
public void mouseClicked(MouseEvent e)
setLayout(new FlowLayout(FlowLayout.LEFT));
{
l1 = new JLabel("Number of mouse String s = "";
clicks:");
s + = ++nb;
l2 = new JLabel("0");
l2.setText (s);
add(l1);
add(l2);
}
addMouseListener(new ListenMouse());
}
76
Exercise
— Solution 2: Create an anonymous class that inherits from
MouseAdapter

…… ..
l1 = new JLabel("Number of mouse clicks:");
l2 = new JLabel("0");
add(l1);
add(l2);

addMouseListener(new MouseAdapter() {public void


mouseClicked(MouseEvent e)
{
String s = "";
s + = ++ nb;
l2.setText(s);

}
}
);
77
Exercise
— Write a program that displays a window on which there are 2
controls.
— The first is preceded by a Dollar label
— The second of a Riyal label.
— When the user enters a number in the first field, its conversion
into Dinars appears simultaneously in the second field.

78
Solution
import javax.swing. *;
import java.awt. *;
import java.awt.event. *;
import java.text.DecimalFormat;
public class Window extends JFrame{
private JLabel l1, l2, l3;
private JTextField t1, t2;
public Window ()
{ setLocation(250,250);
setTitle("Converter");
setSize(300.60);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
JPanel p = (JPanel)this.getContentPane();
setLayout(new GridLayout(1.5));
l1 = new JLabel("Euros");
l2 = new JLabel("=");
l3 = new JLabel("Dinars");
t1 = new JTextField();
t2 = new JTextField();
79 add(l1); add(t1); add(l2); add(l3); add(t2);
Solution
t1.addFocusListener(new FocusAdapter(){public void focusLost(FocusEvent e) {
double d =Double.parseDouble(t1.getText());
String s = "";
d = d * 2.2;
DecimalFormat df = new DecimalFormat("###. ###");

s + = d;
t2.setText(df.format(d));
}});

}
public static void main (String [] args) {
Window fen = new Window();
fen.setVisible(true);

}
}

80
Useful methods of the Component class
— The following methods of the Component class allow you to manage the appearance of a
component (including windows):

— public void setVisible ( boolean b): Show and hide a component

— public void setEnabled ( boolean b): Activate and deactivate a component

— public boolean isEnabled (): Find out the state (activated or not) of a component

— public void setBackground ( Color vs ) : Change the background color of a


component

— public void setSize ( int width , int height ) : Change the size of a component

— public void setBounds (int x, int y, int width , int height ) : Change the position
and size of a component

— public Dimension getSize (): return the dimensions of a component. The Dimension
class of the java.awt package contains two public fields: one field height (height) and a
field width (width).
81
The Component JButton
— a JButton is a button that can contain a text label, an icon, or a
combination of the two.

— Among the available manufacturers:


— JButton (String text )
— JButton ( Icon icon)
— JButton (String text , Icon icon)

— Events sent by a button:


— java.awt.event.ActionEvent : is generated when a button is pressed.
— java.awt.event.ChangeEvent: is generated when the internal state of
the button changes, for example, when the mouse pointer hits the
button.
82
the JCheckBox
— a JCheckBoxis a checkbox. It allows the user to make a choice of yes / no
type.

— Among the available manufacturers:


— JCheckBox (String text)
— JCheckBox ( Icon icon)
— JCheckBox (String text, boolean selected)

— Among the available methods:


— public void setSelected( boolean b)
— public boolean isSelected ()

— Event sent by a checkbox:


— Java.awt.ItemEvent, sent when the box changes from "checked" to
"unchecked" or vice versa.

83
the JCheckBox
— Example:
public class Fentre2 extends JFrame implements ItemListener{

private JCheckBox vs;

public Window2 ()
{
………
JPanel p = (JPanel)getContentPane();
p.setLayout(new FlowLayout(FlowLayout.LEFT));
c = new JCheckBox("box 1"); public void itemStateChanged ( ItemEvent e)
p.add (c);
{
c.addItemListener(this);
int state = e.getStateChange () ;
}
if ( state == 1)
System.out.println ("The box is checked");
else
System.out.println ("The box is unchecked");
84 }
the JRadioButton
— a JRadioButton is a radio button. It allows the user to make a choice of
yes / no type.

— Among the available manufacturers:


— JRadioButton (String text)
— JRadioButton ( Icon icon)
— JRadioButton(String text, boolean selected)

— Among the available methods:


— public void setSelected( boolean b)
— public boolean isSelected ()

— Radio buttons are not exclusive. To make them exclusive, they must be
grouped together in aButtonGroup.
85
the JRadioButton

— Event sent by a JRadioButton :

— Java.awt.ItemEvent sent when the state of the radio button changes


from "selected" to "deselected" and vice versa.

86
the JRadioButton
— Example:
public class Fentre2 extends JFrame implements
ItemListener{
private ButtonGroup grp ;
private JRadioButton r1, r2, r3;
public Window2 ()
{ public void itemStateChanged ( ItemEvent e) {
…… ..
grp = new ButtonGroup (); JRadioButton r = ( JRadioButton ) e.getItemSelectable ();
r1 = new JRadioButton ("Java"); String option = r.getText ();
r2 = new JRadioButton ( "VS#" ) ;
r3 = new JRadioButton ("C ++"); System.out.println ("The option" + option + "is the origin
grp.add (r1); grp.add (r2); grp.add (r3); of the event");
p.add (r1); p.add (r2); p.add (r3);
r1.addItemListener(this); boolean state = r.isSelected ();
r2.addItemListener(this); if ( state ) {
r3.addItemListener(this); System.out.println ("The option" + option + "is
} selected");}
else {System.out.println ("The option" + option + "is no
longer selected");}
87 }
the JLabel
— The JLabelwhere labels (or labels) are components that contain text.
They do not have any ornaments, such as a border, and do not react
to user input (no events sent).

— A label is used to identify components that do not have a label, such


as input fields, lists, etc.

— Among the available manufacturers:


— JLabel (String text)
— JLabel (String text, int horizontal alignment )
— Alignment can have one of the values: SwingConstants.LEFT and
SwingConstants.RIGHT.

88
the JLabel
— Among the available methods:

— public void setHorizontalAlignment (int alignment): changes the


alignment of the label.

— public void setText (String text ): modify the text of the label.

— public String getText (): returns the text of the label.

89
the JLabel
— Example:
public class Fentre2 extends JFrame{
private JLabel l1, l2;
public Window2 ()
{
……
JPanel p = (JPanel)getContentPane();
p.setLayout(new BorderLayout());
l1 = new JLabel("label on the right",SwingConstants.RIGHT);
l2 = new JLabel("label on the left",SwingConstants.LEFT);
p.add (l1,BorderLayout.NORTH);
p.add (l2,BorderLayout.SOUTH);
}

90
the JTextField
— a JTextField allows the user to enter and edit a single line of
simple text.

— Among the available manufacturers:

— JTextField (String text )


— JTextField ( int columns) : The number of columns does not limit
the number of characters the user can type. It can introduce longer
chains; however, the entry view scrolls when the text exceeds the
length of the desired field.
— JTextField (String text, int columns )

91
the JTextField
— Among the available methods:
— public void setText (String text) : modify the content of the text field
— public void setColumns ( int columns) : gives the number of characters in
the field. If the formatting manager needs to make the text field larger
or smaller, it can adjust the size.
— public String getText () : returns whatever the user entered in the field,
including leading and trailing spaces.
— public void setFont(): allows you to specify the font in which the text is
displayed.
— Events sent by a JTextField :
— java.awt.ActionEvent sent to type headphones ActionListener when the
user hits the "Enter" key on the keyboard.

92
the JTextField
— The password field JPasswordField is a special type of text field
(subclass of JTextField).

— It is designed to enter passwords.

— The characters typed are not displayed in this field. An echo character
is used instead.

— the method setEchoChar() allows you to choose the character echo to appear
instead of the characters entered by the user.

— getPassword() allows recover the password in an array of characters.


(getText() also allows to recover the password).

93
the JTextField
— Example:
public class Fentre2 extends JFrame implements ActionListener{
private JLabel l1, l2; private JTextField t1; private JPasswordField t2;
public Window2 ()
{
JPanel p = (JPanel)getContentPane();
p.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
p1.setLayout(new GridLayout(1,2)); public void actionPerformed(ActionEvent e)
p2.setLayout(new GridLayout(1,2)); {
l1 = new JLabel("Your password");
t1 = new JTextField(); t1.setText(t2.getText());
t1.setEditable(false); }
p1.add (l1); p1.add (t1);
l2 = new JLabel("Enter your Password");
t2 = new JPasswordField("", 50);
p2.add (l2); p2.add (t2);
t2.addActionListener(this);
p.add (p2,BorderLayout.NORTH); p.add (p1,BorderLayout.SOUTH);
}
94
the JFormattedTextField
— Class JFormattedTextField has a constructor taking as parameter a
Format.This allows tospecify a format in the edit control.
— Classes derived from Format:
— DateFormat
— MessageFormat
— NumberFormat
— Example
// input field for percentages (import the package java.text)
JFormattedTextField cp = new
JFormattedTextField(NumberFormat.getPercentInstance());

95
the JFormattedTextField
// date entry field
JFormattedTextField fieldDate = new
JFormattedTextField(DateFormat.getDateInstance());
// Dec 31, 2000
JFormattedTextField(DateFormat.getDateInstance(DateFormat.SHORT));
// 12/31/2000

— a MaskFormatter suitable for fixed-size patterns (telephone number,


social security number, serial number, etc.).
— List of symbols:
— # => A number
— A => A number or a letter
— ? => A letter
— U => A letter (lowercase are changed to uppercase)
— * => Any character
— L => A letter (upper case is changed to lower case)
— H => Any hexadecimal character (0-9, af or AF)
96
the JFormattedTextField
— Example: For a tel. in Tunisia
— new MaskFormatter("## ## ## ## ##");
(Import the package javax.text)
— You can limit the valid characters by calling one of the
following methods: setValidCharacters(), setInvalidCharacters().
— Example :
// Input control for a box of a chessboard (A1 to H8)
try{
MaskFormatter mask = new MaskFormatter ("U #");
mask.setValidCharacters("ABCDEFGH12345678");
JFormattedTextField case = new JFormattedTextField(mask);
}
catch (ParseException e) {}

97
the JList
— The type list box JList allows you to choose one or more
values from a predefined list. Initially, no value is selected from
the list.

— Among the available manufacturers:


— JList ()
— JList (Object [] list)
— JList(Vector<?> list)

98
the JList
— There are three selection modes for a list box. is therefore
necessary, once the objectJList is constructed, to choose the
selection mode through the method setSelectionMode() :
Selection type
Type parameter value

static int ListSelectionModel.SINGLE_SELECTION a single value (a)


static int a range of values (b)
ListSelectionModel.SINGLE_INTERVAL_SELECTION
static int
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION unrestricted (c)
(Default value)

99
(To) (b) (vs)
the JList
— By default, a list box displays all the items present in the list as far as
the capacity of the container is concerned.
— We can modify this initial behavior so that the visualization of the
list corresponds to the desired appearance:
— by putting the list in a scroll panel JScrollPane :
JList nl= new JList (new Integer [] {100,200,300,400,500,700,800, 900});
JScrollPane jsp = new JScrollPane(nl);
— by defining the number of elements to display:
nl.setVisibleRowCount(3);
— by proposing a particular color for selection:
nl.setSelectionBackground(Color.black);
nl.setSelectionForeground(Color.red);

100
the JList
— Methods available to retrieve the selected values:

— Single-selection list:
— public Object getSelectedValue(). It provides the (only) selected object. Sometimes you
will need to do an explicit conversion to use this object.

— Multiple selection list


— public Object [] getSelectedValues ()

— It is possible to retrieve the position of the selected objects instead of


their values:
— public int getSelectedIndex ()
— public int [] getSelectedIndices ()

101
the JList
— Event sent by a JList :

— Javax.swing.event.ListSelectionEvent sent when an item in the list is


selected.
— Listeners for this event must implement the interface
Javax.swing.event.ListSelectionListener which contains only one
method:
— public void valueChanged().

102
the JComboBox
— a JComboBox is a combo list box (combo box). It combines a
text field and a single-select list box. As long as the component is
not selected, only the text field is displayed.

— When the user selects the text field, the list box is displayed

— Among the manufacturers:


— JComboBox ()
— JComboBox (Object [] elements)
— JComboBox ( Vector<?> elements)

103
the JComboBox
— It is possible to insert or delete new elements from a drop-down
list:

— addItem(Object e): add a new element at the end of the list


— insertItemAt(Object e, int pos): insert a new element at a specific
location.
— removeAllItems(): delete all elements
— removeItem(Object e): delete a specific item
— removeItemAt(int pos): remove an element by specifying its position.
— getItemCount(): allows you to find out the number of items already
present.

104
the JComboBox
— It is possible to force selection:
— of an element of rank given by setSelectedIndex(int)
— of particular value through setSelectedItem(Object)
— To retrieve the selected item:
— public Object getSelectedItem(): provides the selected value, whether it is a
predefined value or entered in the associated text field.
— public int getSelectedIndex() also provides the rank of the value selected (-1
when the user enters a new element).
— Default one JComboBox is not editable.
— The method setEditable() makes it editable.
— Entering an element only modifies the current element and does not
change the content of the list.

105
the JComboBox
— Event sent by a JComboBox:

— Java.event.ActionEvent when selecting a value from the list or when


validating the text field (when it is editable).

— Java.event.ItemEvent each time the selection is changed

106
The toolbar (JToolBar)
— A JToolBar can be placed on the edges (and not in the
center!) a container fitted with a BorderLayout
— Do not put anything other than a component (JPanel for
example) in the center and the JToolBar

107
107
The toolbar (JToolBar)
— Use a BoxLayout
— Can come off if it is floatable
(setFloatable(boolean b);)
— When we close a JToolBar floating, it returns to its last
position.

108
108
The toolbar (JToolBar)

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

public class TestBarTools {


public static void main (String [] args) {
JFrame f = new JFrame("Example with toolbar");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension (600, 400));
f.setLocation(100, 100);
JPanel p = (JPanel) f.getContentPane();

JPanel pCenter = new JPanel();


pCentre.setBackground(Color.CYAN);
p.add (pCenter, BorderLayout.CENTER);

109
109
The toolbar (JToolBar)

JToolBar toolbar = new JToolBar(JToolBar.HORIZONTAL);


//toolbar.setFloatable(false);
JButton b1 = new JButton("Button 1");
toolbar.add (b1);
JButton b2 = new JButton("Button 2");
toolbar.add (b2);
JButton b3 = new JButton("Button 3");
toolbar.add (b3);

p.add (toolbar, BorderLayout.NORTH);

f.pack();
f.setVisible(true);
}
}

110
110
the JMenuBar, the JMenu and the
JMenuItem
— a JMenu is a standard drop-down menu with a fixed name. The
menus can contain other menus in (sub-menus), which makes it
possible to set up complex menu structures.
— a JMenuBar is a component that hosts menus in a horizontal
bar. Menu bars can be placed anywhere in a container
— An object JMenuItem is a menu option.
JMenuBar
JMenu

JMenuItem

JMenu JMenuItem

111
the JMenuBar, the JMenu and the
JMenuItem
— The method setEnabled(boolean) of style JComponent allows you to
activate or deactivate a menu or a menu option.

— The menu creation steps:

— Creation of a menu bar instance of JMenuBar


— Addition of the bar to the window directly (and not at contentPane).
— Creation of menus instances of JMenu
— Creation of options for each menu instances of JMenuItem
— Attach an action to each menu option
112
the JMenuBar, the JMenu and the
JMenuItem
— Builder of JMenuBar :
— JMenuBar ()

— Builder of JMenu :
— JMenu(String s)

— Builders of JMenuItem :
— JMenuItem ( Icon icon)
— JMenuItem ( String text)
— JMenuItem ( String text, Icon icon)
— JMenuItem ( String text, int mnemonic)
113
the JMenuBar, the JMenu and the
JMenuItem
— Among the methods of JMenuBar available:
— public JMenu add ( JMenu vs )
— public JMenu getMenu ( int index)
— public int getMenuCount ()
— Among the methods of JMenu available:
— public JMenuItem add ( JMenuItem menuItem )
— public JMenuItem add (String s)
— public void addSeparator ()
— public JMenuItem getItem ( int pos)
— public void remove ( JMenuItem item)
— Among the methods of JMenuItem available:
— public void setEnabled ( boolean b)
114
— public boolean isEnabled ()
the JMenuBar, the JMenu and the
JMenuItem
— Events sent:

— Selecting an option (JMenuItem) generates an event of type


java.event.ActionEvent

— We can use the method getActionCommand() of style ActionEvent,


which like a button, provides the command string associated with the
option. By default, this is simply the name of the option (supplied to the
constructor ofJMenuItem).

115
Example:
public class Fenetre13 extends JFrame{
JMenuBar menu bar = new JMenuBar ();
JMenu shapes = new JMenu ("Shapes");
JMenu rounded = new JMenu ( "Round" ) ;
JMenuItem circle = new JMenuItem ("Circle");
JMenuItem oval = new JMenuItem ("Oval");
JMenuItem rectangle = new JMenuItem ("Rectangle");
public Fenetre13 () {
...
setJMenuBar(menu bar);
barMenus.add (shapes);
shapes.add (rounded);
shapes.add (rectangle);

rounded.add (circle);
rounded.add (oval);
}
116
the JMenuBar, the JMenu and the
JMenuItem
— The JMenu may contain:
— special buttons: JMenuItem,
— submenus of type JMenu
— JRadioButtonMenuItem,
— JCheckBoxMenuItem
— separators: addSeparator()

117
the JMenuBar, the JMenu and the
JMenuItem
— 3 selection modes:
— mouse click
— keyboard validation with Enter
— mnemonic (underlined character) or keyboard shortcut

118
the JMenuBar, the JMenu and the
JMenuItem
— to install a Mnemonic:
— File.setMnemonic('F')

— to create a keyboard shortcut:


miNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_NOT,
Event.CTRL_MASK));

— Icon: Icon img = new ImageIcon("new.jpg");


miNew.setIcon(img);
— Sometimes you need to add the URL of the icon to make it appear.

— Information bubble: miOuvrir.setToolTipText("Allows you to open a


119 new file");
Exercise
— Implement the following interface:

120
Solution
import java.awt. *;
import java.awt.event. *;
import javax.swing. *;

public class TestMenus extends JFrame implements ActionListener


{

public TestMenus() {
super ("Example with menu bar");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension (600, 400));
setLocation(100, 100);
JPanel p = (JPanel) getContentPane();

121
121
Solution
JMenuBar mb = new JMenuBar();
JMenu mFile = new JMenu("File");
mFile.setMnemonic('F');
JMenuItem miNew = new JMenuItem("New");
miNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
Event.CTRL_MASK));
Icon img = new ImageIcon("icons / new.jpg");
miNew.setIcon(img);
mFile.add (miNew);

JMenuItem miOpen = new JMenuItem("To open");


miOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
Event.CTRL_MASK));
miOuvrir.setToolTipText("Allows you to open a new file");

122
122
Solution
miOpen.addActionListener(this);
mFile.add (miOpen);

JMenuItem miPrint = new JMenuItem("To print");


mFile.add (miPrint);

mFile.add (new JSeparator(JSeparator.VERTICAL));


//mFile.addSeparator();

JMenuItem miSave = new JMenuItem("Save");


miSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
Event.CTRL_MASK));
miSave.addActionListener(this);
mFile.add (miSave);

123
123
Solution
JMenuItem miSaveUnder = new JMenuItem("Save as");
mFile.add (miSaveUnder);
mFile.add (new JSeparator(JSeparator.HORIZONTAL));
JMenuItem to leave = new JMenuItem("To leave");
miQuitter.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
Event.CTRL_MASK));
miQuitter.addActionListener(this);
mFile.add (to leave);

mb.add (mFile);
JMenu Editing = new JMenu("Editing");
mEdition.setMnemonic('E');

mb.add (Editing);

124
124
Solution
JMenu mDisplay = new JMenu("Display");
mAdisplay.setMnemonic('TO');
JMenu mPolice = new JMenu("Police");
ButtonGroup bg = new ButtonGroup();
JRadioButtonMenuItem font1 = new JRadioButtonMenuItem("Time new
Romain");
JRadioButtonMenuItem font2 = new JRadioButtonMenuItem("Arial");
JRadioButtonMenuItem font3 = new JRadioButtonMenuItem("comic
without MS ");
bg.add (font1);
bg.add (font2);
bg.add (font3);
mPolice.add (font1);
mPolice.add (font2);
mPolice.add (font3);

125
125
Solution

mPolice.add (new JSeparator(JSeparator.HORIZONTAL));

JCheckBoxMenuItem font1 = new JCheckBoxMenuItem("Fat");


JCheckBoxMenuItem font2 = new JCheckBoxMenuItem("Italics");
JCheckBoxMenuItem font3 = new JCheckBoxMenuItem("Underline");
mPolice.add (font1);
mPolice.add (font2);
mPolice.add (font3);

mdisplay.add (mPolice);
mb.add (mDisplay);
setJMenuBar(mb);

126
126
Dialogs
— A dialog is a container. It allows you to group any components in
a kind of window that you make appear or disappear.

— Java provides a number of standard dialog boxes obtained using


methods of the class JOptionPane : message boxes, confirmation
boxes, input boxes and option boxes.
— Class JDialog allows you to build custom dialog boxes.

127
Dialogs
— Message boxes
— A message box provides the user with a message that remains
displayed until the user acts on the OK button. It is built using the
class method
static void showMessageDialog (parent, message)
of style JOptionPane.
— Example
JOptionPane.showMessageDialog ( null , "Hello" ) ;}}

128
Dialogs
— There is a variant of the method showMessageDialog() which
allows you to choose the title of the box and the type of icon
among the elements of the following table (the parameters are
integer constants of the class JOptionPane).

Setting Icon type


static int JOptionPane.ERROR_MESSAGE Fault
static int JOptionPane.INFORMATION_MESSAGE Information
static int JOptionPane.WARNING_MESSAGE Warning
static int JOptionPane.QUESTION_MESSAGE Question
static int JOptionPane.PLAIN_MESSAGE No icon

129
Dialogs
— Example
— JOptionPane.showMessageDialog(parentWindow, content, title,type_icone);
— JOptionPane.showMessageDialog ( null, "warning", "box title", JOptionPane.
WARNING_MESSAGE);

130
Dialogs
— Entry boxes
— An input box allows the user to provide information in the form of a
character string.
— She is constructed using the class method
Static String showInputDialog (parent, message) of style JOptionPane.
— Example
— JOptionPane.showInputDialog ( null , " Enter the first integer");

— The return value of the method showInputDialog is either a type


object String containing the text provided by the user, i.e. the value
null if the user has not confirmed their entry with the OK button.
131
Dialogs

— There is a variant of the method showInputDialog who also allows


you to choose the title of the box and the type of icon.
— Example
— JOptionPane.showInputDialog (null, "Enter your name", "Identity check",
JOptionPane.WARNING_MESSAGE);

132
Dialogs
— Exercise:
— Write a program allowing to ask the user to give two integers and to
display their sum thereafter.
— NB: Use the dialogue boxes to answer the exercise.

133
Dialogs
— The option boxes:
— An options box allows the user to choose a value from a list of values, via
a combo box. It is built using the class method
— static Object showInputDialog (arg1, arg2, arg3, arg4, arg5, arg6, arg7)
of style JOptionPane.

— The return value of the method showInputDialog is either a Object


containing the value selected by the user, or null if the user did not
confirm his entry using the button OK.

— Example
String [] colors = {"red", "blue", "gray", "green", "yellow", "black"};
JOptionPane.showInputDialog(null, "Choose a color", "Options box",
134
JOptionPane.QUESTION_MESSAGE, null, colors, colors [1]);
Dialogs
— Confirmation boxes
— A confirmation box offers the user a choice of yes / no / cancel.
— It is built using the class method:

static int showConfirmDialog (parentWindow, message)

of style JOptionPane.

JOptionPane.showConfirmDialog ( null, "Do you want to continue ?" );

135
Dialogs
— There is a variant of the method showConfirmDialog() who allows
you to choose the title of the box and the nature of the buttons found
there among the elements of the following table (the parameters are
integer constants of the class JOptionPane).

Setting Box type


JOptionPane.DEFAULT_OPTION Fault
JOptionPane.YES_NO_OPTION buttonsYES and NO
JOptionPane.YES_NO_CANCEL_OPTION YES, NO and CANCEL buttons
JOptionPane.OK_CANCEL_OPTION OK and CANCEL buttons

136
Dialogs
— Example
— int n = JOptionPane.showConfirmDialog ( null, "Do you want to continue?", "Major
incident", JOptionPane.YES_NO_OPTION );

— The return value of the method showConfirmDialog specifies the action taken
by the user as an integer having one of the following constants:
— JOptionPane.YES_OPTION (0),
— JOptionPane.OK_OPTION (0),
— JOptionPane.NO_OPTION (1),
— JOptionPane.CANCEL_OPTION (2),
— JOptionPane.CLOSED_OPTION (-1).

137
138
— The results will be on JOptionPane with this Format:
Number op number = result
— The exceptions scenarios:
— Warning for the same numbers value
— In / the second number is 0,

139

You might also like