��نسخة chapter 2�
��نسخة chapter 2�
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.
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.
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.
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.
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.
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
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:
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.
23
The window JFrame
For closing the window to end the program, add:
setDefaultCloseOperation ( JFrame.EXIT_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:
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. *;
26
The window JFrame
Reposition and resize a window:
setBounds(px, py, l, h)
With:
px and py: the coordinates of the pixel which presents the new position of the
window.
27
The window JFrame
Reposition and resize a window:
import javax.swing. *;
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).
But the method add always add the component in the same place
in the container.
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();
35
Absolute positioning
To place components at a specific location, we must indicate
that we do not use LayoutManager.
ContainerObject.setLayout(null);
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.
37
Presentation managers
Any container has a default GP.
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.
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.
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
45
BorderLayout
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.
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.
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.
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{
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);
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.
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).
Any listener of a component must register with this component using the
method addXXXListener().
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
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.
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.
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
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
69
Exercise
Indication:
addMouseListener(this);
}
71
Solution
public void mouseClicked(MouseEvent e)
{
String s = "";
s + = ++ nb;
l2.setText(s);
72
Adapters
Reminder: a class which implements an interface must redefine
all the methods of the interface
73
Adapters
Instead of implementing the interface, it will suffice to inherit
from the Adapter class.
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);
}
}
);
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 boolean isEnabled (): Find out the state (activated or not) 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.
83
the JCheckBox
Example:
public class Fentre2 extends JFrame implements ItemListener{
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.
Radio buttons are not exclusive. To make them exclusive, they must be
grouped together in aButtonGroup.
85
the JRadioButton
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).
88
the JLabel
Among the available methods:
public void setText (String text ): modify 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.
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).
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.
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
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.
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
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.
101
the JList
Event sent by a JList :
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
103
the JComboBox
It is possible to insert or delete new elements from a drop-down
list:
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:
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. *;
109
109
The toolbar (JToolBar)
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.
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:
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')
120
Solution
import java.awt. *;
import java.awt.event. *;
import javax.swing. *;
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);
122
122
Solution
miOpen.addActionListener(this);
mFile.add (miOpen);
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
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.
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).
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");
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.
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:
of style JOptionPane.
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).
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