ce203 - application programming autumn 2013ce203 part 71 part 7

50
CE203 - Application Programming Autumn 2013 CE203 Part 7 1 Part 7

Upload: jude-soldan

Post on 31-Mar-2015

220 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 - Application Programming

Autumn 2013 CE203 Part 7 1

Part 7

Page 2: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 2Autumn 2013

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.

Page 3: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 3Autumn 2013

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 usec.setLayout(new BorderLayout(30,20));

orc.setLayout(new FlowLayout(30,20));

Page 4: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 4Autumn 2013

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); c.setLayout(f);// add several components to cf.setHgap(40);f.layoutContainer(c);

Page 5: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 5Autumn 2013

Layout Managers 4

When a FlowLayout object is being used it is possible to specify left- or right- alignment instead of the default centre-alignment. This may be done using a constructor:FlowLayout f = new FlowLayout( FlowLayout.RIGHT);

or later by using the method setAlignment:f.setAlignment(FlowLayout.CENTER);

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.

Page 6: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 6Autumn 2013

Layout Managers 5

We can specify both the alignment and the gaps when creating a FlowLayout object by using a three-argument constructor:c.setLayout(new FlowLayout( FlowLayout.LEFT,20,10));

Page 7: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 7Autumn 2013

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));

Page 8: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 8Autumn 2013

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 formc.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.

Page 9: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 9Autumn 2013

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).

Page 10: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 10Autumn 2013

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 vertically:c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));for (int i = 1; i<4; i++) c.add(new JButton("Button "+i));

Page 11: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 11Autumn 2013

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 useBox 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.

Page 12: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 12Autumn 2013

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.

Page 13: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 13Autumn 2013

The GridBagLayout Class 2

The 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.)

Page 14: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 14Autumn 2013

The GridBagLayout Class 3

GridBagLayout g = new GridBagLayout();c.setLayout(g);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 1gbc.gridwidth = 2;g.setConstraints(t, gbc); c.add(t);

Page 15: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 15Autumn 2013

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.

Page 16: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 16Autumn 2013

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.

Page 17: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 17Autumn 2013

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 ItemEvent.SELECTED or ItemEvent.DESELECTED.

Page 18: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 18Autumn 2013

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);

Page 19: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 19Autumn 2013

Checkboxes 4

// CBoxExample constructor continued add(new JPanel() { public void paintComponent(Graphics g) { super.paintComponent(g); if (filled) g.fillRect(50,50,100,100); else g.drawRect(50,50,100,100); }, BorderLayout.CENTER); setSize(300, 300); setVisible(true); }

Page 20: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 20Autumn 2013

Checkboxes 5

// class CBoxExample continued public static void main(String args[]) { JFrame myFrame = new CBoxExample(); myFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); } // handler is an inner class class CBHandler implements ItemListener { public void itemStateChanged(ItemEvent e) filled = e.getStateChange()==ItemEvent.SELECTED;

repaint(); }}

Page 21: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 21Autumn 2013

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 selection.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.

Page 22: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 22Autumn 2013

Radio Buttons 2

Event handlers for JRadioButton objects should implement ItemListener.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.

Page 23: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 23Autumn 2013

Radio Buttons 3

// usual imports neededpublic class RadioExample extends JFrame{ JRadioButton redB, blueB, greenB; Color col = Color.red; public RadioExample() { add(new JPanel() { public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(col); g.fillRect(50,50,100,100); } }, BorderLayout.CENTER);

Page 24: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 24Autumn 2013

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(); redB.addItemListener(rbh); blueB.addItemListener(rbh); greenB.addItemListener(rbh); ButtonGroup g = new ButtonGroup(); g.add(redB); g.add(blueB); g.add(greenB);

Page 25: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 25Autumn 2013

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); setVisible(true); } public static void main(String args[]) { JFrame myFrame = new RadioExample(); myFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); }

Page 26: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 26Autumn 2013

Radio Buttons 6

// class RadioExample continued // inner class class RBHandler implements ItemListener { public void itemStateChanged(ItemEvent e) { if (e.getSource()==redB) col = Color.red; else if (e.getSource()==blueB) col = Color.blue; else col = Color.green; repaint(); } }}

Page 27: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 27Autumn 2013

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 JMenuItem.This example on the following slides generates a frame in which the colour of a displayed square is selected from a menu.

Page 28: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 28Autumn 2013

Menus 2

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class MenuExample extends JFrame{ Color col = Color.red; public static void main(String args[]) { JFrame myFrame = new MenuExample(); myFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); }

Page 29: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 29Autumn 2013

Menus 3

// class MenuExample continued public MenuExample() { JMenu menu = new JMenu("Colour"); // add some items to the menu JMenuItem b = new JMenuItem("Blue"); b.addActionListener( new ItemHandler(Color.blue)); menu.add(b); JMenuItem r = new JMenuItem("Red"); r.addActionListener( new ItemHandler(Color.red)); menu.add(r);

Page 30: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 30Autumn 2013

Menus 4

// MenuExample constructor continued // add the menu to a menu bar JMenuBar bar = new JMenuBar(); setJMenuBar(bar); bar.add(menu); setSize(200, 200); setVisible(true); } public void paint(Graphics g) { super.paint(g); g.setColor(col); g.fillRect(50,50,100,100); }

Page 31: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 31Autumn 2013

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; repaint(); } }}

Page 32: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 32Autumn 2013

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.)

Page 33: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 33Autumn 2013

Menus 7

JMenu sqMenu = new JMenu("Square");JMenu sqSizeMenu = new JMenu("Size");// need to add some items to sqSizeMenuJMenu sqColMenu = new JMenu("Colour");// need to add some items to sqColMenusqMenu.add(sqSizeMenu);sqMenu.add(sqColMenu);JMenu circMenu = new JMenu();// need to add submenus and itemsJMenuBar bar = new JMenuBar();setJMenuBar(bar);bar.add(sqMenu); bar.add(circMenu);

Page 34: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 34Autumn 2013

Menus 8When 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 displayed.

Page 35: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 35Autumn 2013

Tabbed Panes 1A 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

Page 36: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 36Autumn 2013

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"); setSize(250,200); setVisible(true); }}

Page 37: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 37Autumn 2013

Dialogue Boxes 1A 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 used:JOptionPane.showMessageDialog(null, "The answer is " + answer, "ANSWER", JOptionPane.INFORMATION_MESSAGE);

Page 38: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 38Autumn 2013

Dialogue Boxes 2The 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, ERROR_MESSAGE, WARNING_MESSAGE, QUESTION_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.

Page 39: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 39Autumn 2013

Dialogue Boxes 3The 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");

Page 40: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 40Autumn 2013

Dialogue Boxes 4There 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” buttons.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.

Page 41: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 41Autumn 2013

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

Page 42: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 42Autumn 2013

Java Security Manager 1

• Java has been designed to work in a distributed environment

• 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 control

Page 43: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 43Autumn 2013

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.

Page 44: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 44Autumn 2013

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 -Djava.security.manager ...

Page 45: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 45Autumn 2013

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 java.security.Policy 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)

Page 46: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 46Autumn 2013

Java Security Manager 5

Sample code snippet: …

Permission perm = new java.io.FilePermission("/tmp/abc", "read");

SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(perm);

}

...

Page 47: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 47Autumn 2013

Java Security Manager 6

http://docs.oracle.com/javase/7/docs/technotes/guides/security/overview/jsoverview.html

Page 48: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 48Autumn 2013

Java Security Manager (Example)

//file: EvilEmpire.javaimport java.net.*;

public class EvilEmpire { public static void main(String[] args) throws Exception{ try { Socket s = new Socket("www.essex.ac.uk", 80); System.out.println("Connected!"); } catch (SecurityException e) { System.out.println("SecurityException: could not connect."); } }} (see Niemeyer and Knudsen, 2005)

Page 49: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 49Autumn 2013

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 –Djava.security.manager EvilEmpire

… and perhaps use your own policy file: C:\> java –Djava.security.manager -Djava.security.policy=EvilEmpire.policy EvilEmpire

(you can of course also use IntelliJ to do this)

Page 50: CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7

CE203 Part 7 50Autumn 2013

Java Security Manager

• This has just been a quick overview.• Check the Java homepage for more details, e.g. http://docs.oracle.com/javase/7/docs/technotes/guides/

security/overview/jsoverview.html