вход по аккаунту

код для вставкиСкачать
CE203 - Application Programming
Part 7
Autumn 2014
CE203 Part 7
Layout Managers 1
Earlier in this module we encountered two layout manager
classes, BorderLayout and FlowLayout, and saw that we
may specify a layout manager for a container by applying
setLayout. If this method is not called a border layout
manager is used for the container of an applet or frame, but a
flow layout manager is used for a panel.
Autumn 2014
CE203 Part 7
Layout Managers 2
When a BorderLayout or FlowLayout object is created it is
possible to specify the size of the horizontal and vertical gaps
that separate the components; if this is not done there will be
no gaps. To obtain horizontal spacing of 30 pixels and
vertical spacing of 20 pixels we could use
c.setLayout(new BorderLayout(30,20));
c.setLayout(new FlowLayout(30,20));
Autumn 2014
CE203 Part 7
Layout Managers 3
The spacing may be altered after the layout manager has been
created using setVgap and setHgap. If either of these is
called after components have been added to the container, the
layout of these components will not be updated unless we call
the method layoutContainer.
FlowLayout f = new FlowLayout(10,10);
// add several components to c
Autumn 2014
CE203 Part 7
Layout Managers 4
When a FlowLayout object is being used it is possible to
specify left- or right- alignment instead of the default centrealignment. This may be done using a constructor:
FlowLayout f = new FlowLayout(
or later by using the method setAlignment:
If we wish to change the alignment of components that have
already been added we must, as on the previous slide, call the
method layoutContainer.
Autumn 2014
CE203 Part 7
Layout Managers 5
We can specify both the alignment and the gaps when
creating a FlowLayout object by using a three-argument
c.setLayout(new FlowLayout(
Autumn 2014
CE203 Part 7
The GridLayout Class 1
The GridLayout manager class may be used to arrange
components in rows and columns. This manager uses a
regular grid; each component will have the same size. The
following code fragment will place twelve buttons in three
rows of four.
c.setLayout(new GridLayout(3,4));
for (int i = 1; i<12; i++)
c.add(new JButton(""+i));
Autumn 2014
CE203 Part 7
The GridLayout Class 2
The two arguments passed to the constructor specify the
number of rows and number of columns. A four-argument
version is available which allows gaps between components
to be specified; a call of the form
c.setLayout(new GridLayout(5,6,10,12));
will create a grid comprising five rows and six columns with
a horizontal spacing between components of 10 pixels and a
vertical spacing of 12 pixels.
Autumn 2014
CE203 Part 7
The GridLayout Class 3
When components are added to a container using a grid
layout manager the grid is always filled row-by-row (starting
with the top row), each row being filled from left to right. If
gaps in the grid are required it is necessary to add dummy
components (e.g. empty labels).
Autumn 2014
CE203 Part 7
The BoxLayout Class
The BoxLayout class can be used to align a group of
components horizontally or vertically. It has a constructor
with two arguments specifying the identity of the container
and whether the layout is horizontal or vertical. The
following code would arrange a group of buttons aligned
c.setLayout(new BoxLayout(c,
for (int i = 1; i<4; i++)
c.add(new JButton("Button "+i));
Autumn 2014
CE203 Part 7
The Box Class
Although box layout can be used as the manager for a panel it
is more convenient to create an object of type Box instead of
a JPanel object. This class always uses a box layout manager
so setLayout is not used. To arrange a group of buttons in a
box on the left of a frame or applet we could use
Box b = Box.createVerticalBox();
for (int i = 1; i<4; i++)
b.add(new JButton("Button "+i));
c.add(b, BorderLayout.WEST);
The Box class has methods that allow control of the spacing
between the components but these are quite complex.
Autumn 2014
CE203 Part 7
The GridBagLayout Class 1
To obtain more control over the positioning of components
on a grid it is possible to use the GridBagLayout class. This
allows components to be added in any order to specific
locations on the grid and to straddle multiple locations. It also
allows the sizes of the rows and columns to vary.
In order to use this manager an object of type
GridBagConstraints must be created. Details of where on
the grid a component is to be placed should be placed in this
object before the component is added to the grid; the
setConstraints method is used to apply these constraints
to the manager before calling add.
Autumn 2014
CE203 Part 7
The GridBagLayout Class 2
gridx and gridy instance variables of the
GridBagConstraints object are used to indicate in which
row and column a component is to be placed.
The code fragment on the next slide shows the placing of a
label in column 0 on row 0 of a grid, with a button in column
1 on row 0. A text field is added occupying both columns 1
and 2 on row 1, a gridwidth value being used to indicate
that it should straddle two columns – the gridx value in this
case indicates the first of the columns. (To straddle multiple
rows we would set the gridheight value.)
Autumn 2014
CE203 Part 7
The GridBagLayout Class 3
GridBagLayout g = new GridBagLayout();
GridBagConstraints gbc =
new GridBagConstraints();
JLabel l = new JLabel("Hello");
gbc.gridx = 0; gbc.gridy = 0;
g.setConstraints(l, gbc); c.add(l);
JButton b = new JButton("b1");
gbc.gridx = 1;
// gridy still 0
g.setConstraints(b, gbc); c.add(b);
JTextField t = new JTextField(20);
gbc.gridy = 1;
// gridx still 1
gbc.gridwidth = 2;
g.setConstraints(t, gbc); c.add(t);
Autumn 2014
CE203 Part 7
The GridBagLayout Class 4
The number of rows and columns in the grid is determined by
the grid positions of the items added – in the example,
assuming that no more items were added, there would be two
rows of three columns.
The width of each column and height of each row is by
default equal to the width or height of the largest component
in that column or row, but this can be changed by setting
values in the GridBagConstraints object.
For more details of the use of the box layout and grid bag
layout managers see (e.g.) Deitel and Deitel section 22.9.
Autumn 2014
CE203 Part 7
Checkboxes 1
A checkbox is a state button that has a boolean value, usually
denoting whether some feature is to be turned on or off.
Objects of type JCheckBox may be added to a frame, applet
or panel in the same way as any other component, but the
handler for the box is different. Instead of adding an action
listener to the box we need to add an item listener which
implements the class ItemListener by providing a void
method called itemStateChanged with an argument of type
ItemEvent. This method will be called whenever the user
clicks on the box to turn it on or off.
Autumn 2014
CE203 Part 7
Checkboxes 2
The program on the following slides shows how a checkbox
may be used to control whether a square displayed on a panel
is to be filled or drawn as an outline.
Note that the JCheckBox constructor takes a string argument,
the label for the box.
Within the event-handler we examine the event using the
getStateChange method, which will return either
Autumn 2014
CE203 Part 7
Checkboxes 3
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CBoxExample extends JFrame
{ boolean filled = false;
public CBoxExample()
{ super("Check box example");
JCheckBox cb = new JCheckBox("fill");
cb.addItemListener(new CBHandler());
add(cb, BorderLayout.SOUTH);
Autumn 2014
CE203 Part 7
Checkboxes 4
// CBoxExample constructor continued
add(new JPanel()
{ public void paintComponent(Graphics g)
{ super.paintComponent(g);
if (filled)
setSize(300, 300);
Autumn 2014
CE203 Part 7
Checkboxes 5
// class CBoxExample continued
public static void main(String args[])
{ JFrame myFrame = new CBoxExample();
// handler is an inner class
class CBHandler implements ItemListener
{ public void itemStateChanged(ItemEvent e)
filled =
Autumn 2014
CE203 Part 7
Radio Buttons 1
Radio buttons are similar to checkboxes, but may be grouped
together and at any time exactly one button from a group will
be selected; clicking on another one will deselect the previous
Radio buttons are placed on a frame, applet or panel as
individual components; the grouping is performed as a
separate activity by adding the buttons to an object of type
ButtonGroup; this object is not a component so it is not
added to the container.
Autumn 2014
CE203 Part 7
Radio Buttons 2
Event handlers for JRadioButton objects should implement
The example on the following slides shows the use of radio
buttons to control the colour of a square. Note the use of the
boolean argument in the calls to the JRadioButton
constructor to indicate which button is initially selected.
The ItemEvent class has a getSource method similar to that
of ActionEvent; this has been used in the button handler to
determine which radio button the user has selected.
Autumn 2014
CE203 Part 7
Radio Buttons 3
// usual imports needed
public class RadioExample extends JFrame
{ JRadioButton redB, blueB, greenB;
Color col =;
public RadioExample()
{ add(new JPanel()
{ public void paintComponent(Graphics g)
{ super.paintComponent(g);
Autumn 2014
CE203 Part 7
Radio Buttons 4
// RadioExample constructor continued
redB = new JRadioButton("red", true);
blueB = new JRadioButton("blue" false);
greenB = new JRadioButton("green", false);
RBHandler rbh = new RBHandler();
ButtonGroup g = new ButtonGroup();
Autumn 2014
CE203 Part 7
Radio Buttons 5
// RadioExample constructor continued
JPanel p = new JPanel();
p.setLayout(new FlowLayout(10,0));
p.add(redB); p.add(blueB); p.add(greenB);
add(p, BorderLayout.SOUTH);
setSize(300, 300);
public static void main(String args[])
{ JFrame myFrame = new RadioExample();
Autumn 2014
CE203 Part 7
Radio Buttons 6
// class RadioExample continued
// inner class
class RBHandler implements ItemListener
{ public void itemStateChanged(ItemEvent e)
{ if (e.getSource()==redB)
col =;
else if (e.getSource()==blueB)
col =;
else col =;
Autumn 2014
CE203 Part 7
Menus 1
In order to use menus in a frame or applet we need to add a
menu bar. This contains one or more menus, which are
made up of menu items (or submenus).
Hence three classes need to be used: JMenuBar, JMenu and
This example on the following slides generates a frame in
which the colour of a displayed square is selected from a
Autumn 2014
CE203 Part 7
Menus 2
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MenuExample extends JFrame
{ Color col =;
public static void main(String args[])
{ JFrame myFrame = new MenuExample();
Autumn 2014
CE203 Part 7
Menus 3
// class MenuExample continued
public MenuExample()
{ JMenu menu = new JMenu("Colour");
// add some items to the menu
JMenuItem b = new JMenuItem("Blue");
new ItemHandler(;
JMenuItem r = new JMenuItem("Red");
new ItemHandler(;
Autumn 2014
CE203 Part 7
Menus 4
// MenuExample constructor continued
// add the menu to a menu bar
JMenuBar bar = new JMenuBar();
setSize(200, 200);
public void paint(Graphics g)
{ super.paint(g);
Autumn 2014
CE203 Part 7
Menus 5
// class MenuExample continued
class ItemHandler implements ActionListener
{ private Color theCol;
public ItemHandler(Color colour)
{ theCol = colour;
public void actionPerformed(ActionEvent e)
{ col = theCol;
Autumn 2014
CE203 Part 7
Menus 6
Note that the listeners for menu items should implement
ActionListener, not ItemListener.
The setJMenuBar method is used to associate a menu bar
with an applet or frame; the applet or frame can have only
one menu bar, but the bar may have many menus.
The add method is used to add items or submenus to a menu.
If we were writing a frame with a square and a circle we
might provide a menu for the circle and a menu for the
square, each having submenus to change the colour and size.
An outline of the necessary code is shown on the next slide.
(The addition of action listeners has been omitted.)
Autumn 2014
CE203 Part 7
Menus 7
JMenu sqMenu = new JMenu("Square");
JMenu sqSizeMenu = new JMenu("Size");
// need to add some items to sqSizeMenu
JMenu sqColMenu = new JMenu("Colour");
// need to add some items to sqColMenu
JMenu circMenu = new JMenu();
// need to add submenus and items
JMenuBar bar = new JMenuBar();
bar.add(sqMenu); bar.add(circMenu);
Autumn 2014
CE203 Part 7
Menus 8
When using submenus we should provide action listeners
only for the menu items, and not for the submenus – the
display of submenus is performed automatically when their
names are selected from a menu.
A menu can also contain check boxes and radio buttons of
type JCheckBoxMenuItem or JRadioButtonMenuItem; as
with other menu items we may add action listeners to these
(not item listeners).
Pop-up menus (of type JPopUpMenu) associated with
individual components can be written – mouse listeners must
be added to the components to allow the pop-up menus to be
Autumn 2014
CE203 Part 7
Tabbed Panes 1
A tabbed pane arranges components into layers with only one
layer being visible at a time, the user selecting which is to be
displayed by clicking on a tab at the top of the pane. A
tabbed pane may be added to a panel, frame or applet; it
should normally be the only component added to the
container so if we wish to use other components we should
create a new panel specifically for the tabbed pane.
The JTabbedPane class has a no-argument constructor;
components are added to the pane using the addTab method.
This takes four arguments: a label for the tab, an icon for the
tab (this may be null), the identity of the component and a
tool-tip string. An example is shown on the next slide
Autumn 2014
CE203 Part 7
Tabbed Panes 2
public class MyFrame extends JFrame
{ JTabbedPane tp = new JTabbedPane();
JTextArea t = new JTextArea(………);
JPanel p = new JPanel() { ……… };
public MyFrame()
{ add(tp, BorderLayout.CENTER);
tp.addTab("Text", null, t, "edit text");
tp.addTab("Pict", null, p, "view diagram");
Autumn 2014
CE203 Part 7
Dialogue Boxes 1
A dialogue box is a window that is temporarily placed on the
screen to display a message for the user or allow him or her
to supply input.
To create and display a message dialogue box the static
method showMessageDialog from the JOptionPane class is
"The answer is " + answer,
Autumn 2014
CE203 Part 7
Dialogue Boxes 2
The first argument of the showMessageDialog method, if
non-null, supplies information about the window over which
the dialogue box will appear; by default it appears at the
centre of the screen; in a frame we could use this to indicate
that it should appear in front of the frame. The second
argument is the message to be displayed, the third is a title for
the window and the fourth determines what icon will appear
alongside the message. Options are INFORMATION_MESSAGE,
and PLAIN_MESSAGE (which has no icon).
By default a message dialogue box has an “OK” button at the
bottom which is used to dismiss the window.
Autumn 2014
CE203 Part 7
Dialogue Boxes 3
The JOptionPane class also provides a method called
showInputDialog. This takes just one argument, a prompt
string and will create and display a dialogue box showing an
editable text field below the prompt. Two buttons will be
provided, labelled “OK” and “Cancel”. The method waits
until the user presses one of these buttons then returns a
string – if the “OK” button has been selected the returned
value will contain the text entered in the text field, otherwise
null will be returned.
String name = JOptionPane.showInputDialog(
"Please type your name");
Autumn 2014
CE203 Part 7
Dialogue Boxes 4
There are also methods called showOptionDialog which
allows the programmer to specify the text to be displayed on
a number of buttons and returns a value indicating which
option was selected and showConfirmDialog which can
supply “yes” and “no” buttons or “yes”, “no” and “cancel”
If anything more complex is required the programmer must
create a new JOptionPane object, set its properties, and
create and show a JDialog object, using the option pane as
the argument to the JDialog constructor.
Autumn 2014
CE203 Part 7
Java Swing
• There are many more classes in the Java Swing API
• Try them out using the Java API
• The underlying principles are the same as discussed
throughout the lectures
Autumn 2014
CE203 Part 7
Java Security Manager 1
• Java has been designed to work in a distributed
• Code can be downloaded dynamically from a variety of
(untrusted) sources
• Running such code alongside applications that contain
confidential information poses a potential risk.
• Security is a real concern and built into Java via access
Autumn 2014
CE203 Part 7
Java Security Manager 2
• All access control decisions are done by a security
manager: java.lang.SecurityManager.
• A security manager must be installed into the Java runtime
in order to activate the access control checks.
• Applets are run with a security manager by default.
• Applications have no security manager by default.
Autumn 2014
CE203 Part 7
Java Security Manager 3
Two options to use a security manager:
• Set one via the setSecurityManager method in the
java.lang.System class, i.e..:
System.setSecurityManager(new SecurityManager());
• Call Java using appropriate command line arguments, e.g.:
javac ...
Autumn 2014
CE203 Part 7
Java Security Manager 4
• A small set of default permissions are granted to code by
class loaders. Administrators can then flexibly manage
additional code permissions via a security policy.
• This is done via the class. There
is only one Policy object installed into the Java runtime at
any given time.
• Policy files tell the security manager what is allowed by
whom (and what is not).
• These policies are defined declaratively in text files
(usually created via a policy tool utility)
Autumn 2014
CE203 Part 7
Java Security Manager 5
Sample code snippet:
Permission perm = new"/tmp/abc", "read");
SecurityManager sm =
if (sm != null) {
Autumn 2014
CE203 Part 7
Java Security Manager 6
Autumn 2014
CE203 Part 7
Java Security Manager (Example)
public class EvilEmpire {
public static void main(String[] args) throws
try {
Socket s = new Socket("", 80);
catch (SecurityException e) {
could not connect.");
(see Niemeyer and Knudsen, 2005)
Autumn 2014
CE203 Part 7
Java Security Manager (Example) 2
Run this code without any parameters, e.g. (command line):
C:\> java EvilEmpire
… and with security manager (e.g. command line):
C:\> java – EvilEmpire
… and perhaps use your own policy file:
C:\> java –
(you can of course also use IntelliJ to do this)
Autumn 2014
CE203 Part 7
Java Security Manager
• This has just been a quick overview.
• Check the Java homepage for more details, e.g.
Autumn 2014
CE203 Part 7
Пожаловаться на содержимое документа