CE203 Application Programming - Unit 5 (a) PDF
Document Details

Uploaded by ShinyIridium
University of Essex
2024
Tags
Summary
These are lecture notes for CE203 Application Programming, Unit 5 (a). The topics covered include GUI (Java Swing) Components, Dialogue Boxes, Text fields and Text Areas, Menus and Tabs, and the Graphics class. Code examples are given.
Full Transcript
CE203 - Application Programming Unit 5 (a) CE203 Part 4 1 Learning objectives today GUI (Java Swing) Components – Dialogue Boxes – Text fields and Text Areas (extra) – (Menus and Tabs) – The Graphics Class CE203...
CE203 - Application Programming Unit 5 (a) CE203 Part 4 1 Learning objectives today GUI (Java Swing) Components – Dialogue Boxes – Text fields and Text Areas (extra) – (Menus and Tabs) – The Graphics Class CE203 Part 4 2 Dialogue Boxes: Overview A window that is temporarily placed on 1st argument: window over which dialogue box screen to display a message or allow user to will appear supply input. By default in centre of screen To display a message dialogue box the static In a frame we could use this to indicate that it method showMessageDialog from the should appear in front of the frame. JOptionPane class is used: 2nd argument: message to display. 3rd argument: window title JOptionPane.showMessageDialog(null, "The answer is " + answer, 4th argument: icon alongside the message. "ANSWER", Options: INFORMATION_MESSAGE, JOptionPane.INFORMATION_MESSAGE); ERROR_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE and PLAIN_MESSAGE (no icon). By default a message dialogue box has an “OK” button, which is used to dismiss the window. CE203 Part 4 3 Dialogue Boxes: Options JOptionPane class also provides a method called showInputDialog(). showOptionDialog() specifies One argument: prompt string, displays dialogue box with text to display on buttons and an editable text field below the prompt & two buttons; returns value indicating selection. “OK” and “Cancel”. showConfirmDialog() can Dialog waits until user presses a button then returns a supply “yes” and “no” buttons or string – if the “OK” selected the string contains text entered, otherwise null returned. “yes”, “no” and “cancel” buttons. More complex requirements need String name = new JOptionPane object. JOptionPane.showInputDialog( "Please type your name"); CE203 Part 4 4 Text Fields: Overview Text fields used for the display or input of a single line of text. The java class JTextField has several constructors e.g.: - takes an int, specifying width of field and initialises field to be empty. In the lab we used text fields in an application to calculate the square of a number entered by the user… CE203 Part 4 5 Text Fields: Example public class FilledFrame extends JFrame { JTextField input, result; public FilledFrame() { super(); JLabel prompt = new JLabel("Type a number and press return"); input = new JTextField(5); result = new JTextField(25); // make result field non-editable result.setEditable(false); input.addActionListener( new TextHandler(this)); setLayout(new FlowLayout()); add(prompt); add(input); add(result); } } CE203 Part 4 6 Text Fields: Events // Arith.java continued class TextHandler implements ActionListener { Text field event occurs when private FilledFrame theApp; user completes text entry by pressing the carriage return public TextHandler( FilledFrame app ) { theApp = app; key. } To retrieve contents of text field in actionPerformed() public void actionPerformed(ActionEvent e) { apply getActionCommand to String text = e.getActionCommand(); String answer = null; ActionEvent argument. // clear input field theApp.input.setText(""); setText() in JTextField class try { used to clear input field and int n = Integer.parseInt(text.trim()); display result in output field. answer = "The square is " + n*n; } Note, when the contents of catch(NumberFormatException ex) { components change the answer = "Invalid input"; display is updated immediately } so no repainting is involved. // display the answer theApp.result.setText(answer); } } CE203 Part 4 7 Text Fields: getText public void actionPerformed(ActionEvent e) To retrieve text in a text { field we apply getText to String text = theApp.input.getText(); String answer = null; the JTextField object. theApp.input.setText(""); if (text.length()==0) { answer = "Please enter a number"; } else { // try and catch blocks as before theApplet.result.setText(answer); } } CE203 Part 4 8 Menus: Overview To use menus in a frame 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. The example on the following slides generates a frame in which the colour of a displayed square is selected from a menu. CE203 Part 5 9 Menus: Example public class MenuExample extends Jframe { // add the menu to a menu bar JMenuBar bar = new JMenuBar(); Color col = Color.red; setJMenuBar(bar); public static void main(String args[]) { bar.add(menu); JFrame myFrame = new MenuExample(); setSize(200, 200); setVisible(true); myFrame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); } } public void paint(Graphics g) { super.paint(g); public MenuExample() { g.setColor(col); JMenu menu = new JMenu("Colour"); g.fillRect(50,50,100,100); JMenuItem b = new JMenuItem("Blue"); } b.addActionListener( new ItemHandler(Color.blue) ); menu.add(b); class ItemHandler implements ActionListener { JMenuItem r = new JMenuItem("Red"); private Color theCol; r.addActionListener( new ItemHandler(Color.red) ); public ItemHandler(Color colour) { menu.add(r); theCol = colour; } public void actionPerformed(ActionEvent e){ col = theCol; repaint(); } } } CE203 Part 5 10 Menus: Use Note, listeners for menu items should JMenu sqMenu = new JMenu("Square"); implement ActionListener, not JMenu sqSizeMenu = new JMenu("Size"); ItemListener. // need to add some items setJMenuBar() used to associate menu bar JMenu sqColMenu = new JMenu("Colour"); with a frame // need to add some items to sqColMenu Frames can have only one menu bar, but sqMenu.add(sqSizeMenu); the bar may have many menus. sqMenu.add(sqColMenu); add() adds items or submenus to a menu. JMenu circMenu = new JMenu(); To write frame with a square and a circle // need to add submenus and items we might provide a menu for the circle JMenuBar bar = new JMenuBar(); and a menu for the square, each having setJMenuBar(bar); submenus to change the colour and size. bar.add(sqMenu); bar.add(circMenu); Necessary code is to the right. (Addition of action listeners has been omitted.) CE203 Part 5 11 Menus: Summary When using submenus we should provide action listeners only for menu items, not for the submenus Displaying submenus automatic when 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 5 12 Tabbed Panes: Overview Arranges components into layers with only one layer being visible at a time. A tabbed pane may be added to a panel, frame or applet Normally the only component added to container, to use other components we should create new panels for the tabbed pane. The JTabbedPane class has a no-argument constructor; Components are added to the pane using addTab(). This takes four arguments: a label for the tab an icon for the tab (this may be null) the identity of the component a tool-tip string. An example is shown on the next slide… CE203 Part 5 13 Tabbed Panes: Example 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); } } CE203 Part 5 14 Graphics Methods: Overview Several graphics methods available from the Graphics class; e.g. drawString, setColor, drawRect and fillRect methods Normally used in paint and paintComponent methods, which take argument of type Graphics. (0,10) drawLine() can be used to draw a line; four arguments, the x and y coordinates of each end of the line, so, for example, g.drawLine(0,10,30,40); (30,40) will draw a line from (0,10) to (30,40). CE203 Part 5 15 Graphics Methods: Overview A version of the drawLine() method also takes objects of type Point as (0,10) its arguments. Point is used to represent a location in a two-dimensional (x, y) coordinate space and the previous line can be redefined using Point objects Point p1 = new Point(0, 10); (30,40) Point p2 = new Point(30, 40); g.drawLine(p1.x,p1.y,p2.x,p2.y); will also draw a line from (0,10) to (30,40). You can have a series of Point objects defined and added to a Point array use a for loop to draw lines between each point to form a shape. CE203 Part 5 16 Graphics Methods: Shapes clearRect(): similar to fillRect but draws Draw circle with centre (x,y) and radius r… rectangle in the background colour -top left-hand corner of enclosing (effectively erasing anything displayed). rectangle will be (x-r,y-r) drawOval() and fillOval() produce an oval -width and height of rectangle will be the instead of rectangle. diameter of the circle. These methods take four arguments Hence we would use x-, y-coordinates of top-left g.drawOval(x-r,y-r,2*r,2*r); corner width and height x-r,y-r They draw an oval enclosed by the rectangle specified by the arguments. r If the rectangle is a square, the oval will of x, course be a circle. y CE203 Part 5 17 Graphics Methods: More shapes and fillRoundRect() produce rectangles with rounded corners; drawRoundRect() they have six arguments: -the first four are the same as the arguments of drawRect(), -the last two indicate the width and height of the imaginary oval produced by combining the four arcs at the corners. CE203 Part 5 18 Graphics Methods: Arcs drawArc() and fillArc() produce portion of oval (an The segment shown below would be produced outline or segment); by: 6 arguments: 1-4: the same as drawOval(), g.fillArc(10,10,300,200,10,40); 5: the starting position of the arc (the angle in degrees) 6: number of degrees of arc extension (10,10) (positive numbers = anticlockwise and negative numbers = - clockwise). 40⁰ 10⁰ 200 CE203 Part 5 19 Graphics Methods: Polygons drawPolygon() and fillPolygon() can produce polygons: each takes three arguments: two int arrays containing the x- and y-coordinates respectively of the corners an int indicating the number of corners. For example, to draw a solid triangle with corners at (10,10), (90,70) and (30,110): (10,10) int[] xCoords = { 10, 90, 30 }; (90,70) int[] yCoords = { 10, 70, 110 }; g.fillPolygon(xCoords, yCoords, 3); (30,110) CE203 Part 5 20 Graphics Methods: Multiple polygons If third argument to drawPolygon() or drawPolygon() and fillPolygon() can be used with argument of type Polygon; fillPolygon() is smaller than size of the useful to store information about polygons arrays only part of each array used. before they are drawn. Polygon class has constructor that takes three Thus, same arrays can be reused to arguments similar to those of drawPolygon. draw polygons with different numbers There is also a no-argument constructor that allows of sides. us to add coordinates to polygon one at a time using addPoint method: If the size of either array smaller than third argument an exception is thrown. Polygon p = new Polygon(); p.addPoint(10, 10); See also, drawPolyline() which does p.addPoint(90, 70); not connect last co-ordinate pair from p.addPoint(30, 110); arrays with first pair (i.e. it draws g.drawPolygon(p); incomplete polygon). CE203 Part 5 21 Summary Today we covered – GUI (Java Swing) Components – Dialogue Boxes – Text fields and Text Areas (extra) – (Menus and Tabs) – The Graphics class CE203 Part 4 22