1 / 50

CE203 - Application Programming

CE203 - Application Programming. Part 7. Layout Managers 1.

lilac
Télécharger la présentation

CE203 - Application Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CE203 - Application Programming Part 7 CE203 Part 7

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

  3. 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)); CE203 Part 7

  4. 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); CE203 Part 7

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

  6. 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)); CE203 Part 7

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

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

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

  10. 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)); CE203 Part 7

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

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

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

  14. 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); CE203 Part 7

  15. 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.) Deiteland Deitel section 22.9. CE203 Part 7

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

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

  18. 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"); JCheckBoxcb = new JCheckBox("fill");cb.addItemListener(new CBHandler()); add(cb, BorderLayout.SOUTH); CE203 Part 7

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

  20. 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(); }} CE203 Part 7

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

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

  23. Radio Buttons 3 // usual imports needed public class RadioExample extends JFrame{ JRadioButtonredB, blueB, greenB;Colorcol = 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); CE203 Part 7

  24. 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); CE203 Part 7

  25. Radio Buttons 5 // RadioExample constructor continuedJPanel 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[]) { JFramemyFrame = new RadioExample();myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } CE203 Part 7

  26. 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(); } }} CE203 Part 7

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

  28. 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); } CE203 Part 7

  29. 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); CE203 Part 7

  30. 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); } CE203 Part 7

  31. 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(); } }} CE203 Part 7

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

  33. 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); CE203 Part 7

  34. 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. CE203 Part 7

  35. 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 CE203 Part 7

  36. Tabbed Panes 2 public class MyFrame extends JFrame{ JTabbedPanetp = 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); }} CE203 Part 7

  37. 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); CE203 Part 7

  38. 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. CE203 Part 7

  39. 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"); CE203 Part 7

  40. 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. CE203 Part 7

  41. 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 CE203 Part 7

  42. 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 CE203 Part 7

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

  44. Java Security Manager 3 Two options to use a security manager: • Set one via the setSecurityManagermethod in the java.lang.Systemclass, i.e..: System.setSecurityManager(new SecurityManager()); • Call Java using appropriate command line arguments, e.g.: javac-Djava.security.manager ... CE203 Part 7

  45. 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.Policyclass. 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) CE203 Part 7

  46. Java Security Manager 5 Sample code snippet: … Permission perm = new java.io.FilePermission("/tmp/abc", "read"); SecurityManagersm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(perm); } ... CE203 Part 7

  47. Java Security Manager 6 http://docs.oracle.com/javase/7/docs/technotes/guides/security/overview/jsoverview.html CE203 Part 7

  48. Java Security Manager (Example) //file: EvilEmpire.java import 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) CE203 Part 7

  49. 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.managerEvilEmpire … 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) CE203 Part 7

  50. 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 CE203 Part 7

More Related