Presentation is loading. Please wait.

Presentation is loading. Please wait.

CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7.

Similar presentations

Presentation on theme: "CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7."— Presentation transcript:

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

2 Autumn 2013CE203 Part 72 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.

3 Autumn 2013CE203 Part 73 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)); or c.setLayout(new FlowLayout(30,20));

4 Autumn 2013CE203 Part 74 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 c f.setHgap(40); f.layoutContainer(c);

5 Autumn 2013CE203 Part 75 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.

6 Autumn 2013CE203 Part 76 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));

7 Autumn 2013CE203 Part 77 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));

8 Autumn 2013CE203 Part 78 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.

9 Autumn 2013CE203 Part 79 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).

10 Autumn 2013CE203 Part 710 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));

11 Autumn 2013CE203 Part 711 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.

12 Autumn 2013CE203 Part 712 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.

13 Autumn 2013CE203 Part 713 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.)

14 Autumn 2013CE203 Part 714 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 1 gbc.gridwidth = 2; g.setConstraints(t, gbc); c.add(t);

15 Autumn 2013CE203 Part 715 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.

16 Autumn 2013CE203 Part 716 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.

17 Autumn 2013CE203 Part 717 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.

18 Autumn 2013CE203 Part 718 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);

19 Autumn 2013CE203 Part 719 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); }

20 Autumn 2013CE203 Part 720 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(); } }

21 Autumn 2013CE203 Part 721 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.

22 Autumn 2013CE203 Part 722 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.

23 Autumn 2013CE203 Part 723 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); g.setColor(col); g.fillRect(50,50,100,100); } }, BorderLayout.CENTER);

24 Autumn 2013CE203 Part 724 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);

25 Autumn 2013CE203 Part 725 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); }

26 Autumn 2013CE203 Part 726 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 =; repaint(); } } }

27 Autumn 2013CE203 Part 727 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.

28 Autumn 2013CE203 Part 728 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(); myFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); }

29 Autumn 2013CE203 Part 729 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(; menu.add(b); JMenuItem r = new JMenuItem("Red"); r.addActionListener( new ItemHandler(; menu.add(r);

30 Autumn 2013CE203 Part 730 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); }

31 Autumn 2013CE203 Part 731 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(); } } }

32 Autumn 2013CE203 Part 732 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.)

33 Autumn 2013CE203 Part 733 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 sqMenu.add(sqSizeMenu); sqMenu.add(sqColMenu); JMenu circMenu = new JMenu(); // need to add submenus and items JMenuBar bar = new JMenuBar(); setJMenuBar(bar); bar.add(sqMenu); bar.add(circMenu);

34 Autumn 2013CE203 Part 734 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 displayed.

35 Autumn 2013CE203 Part 735 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

36 Autumn 2013CE203 Part 736 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); } }

37 Autumn 2013CE203 Part 737 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 used: JOptionPane.showMessageDialog(null, "The answer is " + answer, "ANSWER", JOptionPane.INFORMATION_MESSAGE);

38 Autumn 2013CE203 Part 738 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, 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.

39 Autumn 2013CE203 Part 739 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");

40 Autumn 2013CE203 Part 740 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” 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.

41 Autumn 2013CE203 Part 741 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

42 Autumn 2013CE203 Part 742 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

43 Autumn 2013CE203 Part 743 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.

44 Autumn 2013CE203 Part 744 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

45 Autumn 2013CE203 Part 745 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)

46 Autumn 2013CE203 Part 746 Java Security Manager 5 Sample code snippet: … Permission perm = new"/tmp/abc", "read"); SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(perm); }...

47 Autumn 2013CE203 Part 747 Java Security Manager 6

48 Autumn 2013CE203 Part 748 Java Security Manager (Example) //file: import*; public class EvilEmpire { public static void main(String[] args) throws Exception{ try { Socket s = new Socket("", 80); System.out.println("Connected!"); } catch (SecurityException e) { System.out.println("SecurityException: could not connect."); } (see Niemeyer and Knudsen, 2005)

49 Autumn 2013CE203 Part 749 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 – EvilEmpire (you can of course also use IntelliJ to do this)

50 Autumn 2013CE203 Part 750 Java Security Manager This has just been a quick overview. Check the Java homepage for more details, e.g. security/overview/jsoverview.html

Download ppt "CE203 - Application Programming Autumn 2013CE203 Part 71 Part 7."

Similar presentations

Ads by Google