Presentation is loading. Please wait.

Presentation is loading. Please wait.

CE203 - Application Programming Autumn 2013CE203 Part 61 Part 6.

Similar presentations


Presentation on theme: "CE203 - Application Programming Autumn 2013CE203 Part 61 Part 6."— Presentation transcript:

1 CE203 - Application Programming Autumn 2013CE203 Part 61 Part 6

2 Autumn 2013CE203 Part 62 Inner Classes 1 In Java a class may be declared within another class; such a class is called an inner class. The methods of an inner class may access private instance variables and methods of the enclosing class. Inner classes are frequently used for the event-handlers in applets and GUI programs. On the following slides we rewrite the square-calculating applet from part 1 of the slides using this approach. Since the inner class may access the members of the Arith2 class so it is no longer necessary to store a reference to the applet in the TextHandler object; hence no constructor is needed.

3 Autumn 2013CE203 Part 63 Inner Classes 2 // usual imports needed public class Arith2 extends JApplet { private JTextField input, result; public void init() { JLabel prompt = new JLabel( "Type a number and press return"); input = new JTextField(5); result = new JTextField(25); result.setEditable(false); setLayout(new FlowLayout()); add(prompt); add(input); add(result); input.addActionListener(new TextHandler()); }

4 Autumn 2013CE203 Part 64 Inner Classes 3 // class Arith2 continued private class TextHandler implements ActionListener { public void actionPerformed(ActionEvent e) { String txt = e.getActionCommand(); input.setText(""); String answer = null; try { int n = Integer.parseInt(txt.trim()); answer = "The square is " + n*n; } catch(Exception ex) { answer = "Invalid input";} result.setText(answer); } } // end of inner class } // end of Arith class

5 Autumn 2013CE203 Part 65 Inner Classes 4 Note that, although the inner class was declared as private, its actionPerformed method had to be declared as public since the class must correctly implement the ActionListener interface. Unless an inner class is declared as static, objects of the class must belong to objects of an outer class so an inner class object can be created only in the non-static methods of the enclosing class.

6 Autumn 2013CE203 Part 66 Inner Classes 5 If an inner class is public we can refer to objects of that class outside of the enclosing class. The following slides present a student class, which contains a public inner class to hold details of all of the student’s examination marks. (The bodies for some of the inner class methods are omitted.) To refer to the inner class ( Marks ) outside of the Student class we need to use Student.Marks. (We have already encountered this notation – Entry is an inner interface of Map.)

7 Autumn 2013CE203 Part 67 Inner Classes 6 public class Student extends Person { private int regno; private Marks marks; public Student(String name, Date dob, int regnum) { super(name, dob); regno = regnum; marks = new Marks(); } public int regNumber() { return regNo; } // will inherit methods to get name and dob

8 Autumn 2013CE203 Part 68 Inner Classes 7 // class Student continued public void addMark(String module, float mark) { marks.add(module, mark); } public Marks getMarks() { return marks; } public String toString() { // body omitted }

9 Autumn 2013CE203 Part 69 Inner Classes 8 // class Student continued public class Marks { private HashMap map; public Marks() { map = new HashMap (); } public void add(String module, float mark) { map.add(module, mark); } public float get(String module) { return map.get(module).floatValue(); } public float getAverage() { …… } public String toString() { …… } } }

10 Autumn 2013CE203 Part 610 Inner Classes 9 Assuming that the variable lisa refers to a Student object holding details about a student called Lisa, we could retrieve and print her marks for CE203 and CE204 using the following code. Student.Marks m = lisa.getMarks(); System.out.println("CE203: " + m.get("CE203") + "CE204: " + m.get(CE204"));

11 Autumn 2013CE203 Part 611 Anonymous Inner Classes 1 When writing applets or GUI components it is often found that an inner class that implements the ActionListener interface has just a single object which is simply created and passed as an argument to the addActionListener method; this is indeed the case for the Arith applet on slides 35-36. The object is effectively anonymous – no variable in our program refers to it. We can take this concept one step further by using an anonymous inner class, which has no name and is simply declared when it is needed. An anonymous inner class must either implement an interface or extend an existing class.

12 Autumn 2013CE203 Part 612 Anonymous Inner Classes 2 The following slide shows how we may rewrite the Arith2 applet using an anonymous inner class. We replace the call to the TextHandler constructor by a call of the form new ActionListener(){……} with the body of the text-handling class in the braces; since this call is an argument to a method it is important not to forget to place a closing parenthesis and semicolon after the brace. Note that, despite the syntax, this code does not actually make a call to an ActionListener constructor (since an interface does not have a constructor); instead the default constructor of the anonymous class is called.

13 Autumn 2013CE203 Part 613 Anonymous Inner Classes 3 // usual imports needed public class Arith3 extends JApplet { private JTextField input, result; public void init() { JLabel prompt = new JLabel( "Type a number and press return"); input = new JTextField(5); result = new JTextField(25); result.setEditable(false); setLayout(new FlowLayout()); add(prompt); add(input); add(result);

14 Autumn 2013CE203 Part 614 Anonymous Inner Classes 4 // Arith 2 init method continued input.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e) { // method body as on slide 4 } } ); } }

15 Autumn 2013CE203 Part 615 Anonymous Inner Classes 5 It is not possible to provide a constructor for an anonymous inner class, since a constructor must have the same name as the class and an anonymous inner class has no name. Hence the compiler will always generate a default constructor which will call the no-argument constructors for any object instance variables. Hence, if an anonymous class has object instance variables they must be of classes that have no-argument constructors. Additionally, if the anonymous class extends another class the constructor will call the no-argument constructor for the superclass so we cannot use anonymous inner classes to extend classes that have no such constructor.

16 Autumn 2013CE203 Part 616 Anonymous Inner Classes 6 We have seen an example of an anonymous inner class that implements an interface. The most common situation where we might use such a class to extend an existing class is when our class contains methods to replace inherited default versions. The GreetingPanel class from the program in part 1 of the slides is a typical example of such a class. Only one object of this class was created and the variable called panel that referred to it can easily be eliminated from the program. On the following slides we rewrite the program using an anonymous inner class.

17 Autumn 2013CE203 Part 617 Anonymous Inner Classes 7 import javax.swing.*; import java.awt.*; public class Greeting3 extends JApplet { public void init() { add(new JLabel("Hello"), BorderLayout.NORTH); // init method continued on next slide // previous version had // add(new GreetingPanel(), // BorderLayout.CENTER);

18 Autumn 2013CE203 Part 618 Anonymous Inner Classes 8 // Greeting3 init method continued add(new JPanel() { public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.blue); g.drawRect(50, 100, 40, 30); g.fillRect(120, 100, 30, 40); } }, BorderLayout.CENTER); } }

19 Autumn 2013CE203 Part 619 Using Frames 1 We have seen various GUI examples written as applets using classes that extend the JApplet class. We shall now see how similar examples can be produced in applications using classes that extend the JFrame class. We start with a frame- based version of the simple greeting program from part 1. (The usual import statements are needed, but have been omitted due to lack of space on the slide.)

20 Autumn 2013CE203 Part 620 Using Frames 2 public class Greeting extends JFrame { public Greeting() { super("Greeting example"); setSize(300, 200); setVisible(true); } public void paint(Graphics g) { super.paint(g); g.drawString("Hello!", 20, 20); g.setColor(Color.blue); g.drawRect(50, 100, 40, 30); g.fillRect(120, 100, 30, 40); } }

21 Autumn 2013CE203 Part 621 Using Frames 3 The JFrame class has a constructor that takes a string argument to specify the contents of the title bar of the window containing the frame. We have invoked this in our constructor using super. We have also used the constructor to specify the size of the frame. A frame is not displayed until it is explicitly made visible so we need to make a call to the setVisible method; this could be done elsewhere (e.g. in a main method that creates a frame object) if we did not write a constructor.

22 Autumn 2013CE203 Part 622 Using Frames 4 We need a main method to create a Greeting object; this could be placed in a separate class in a separate file: public class Greet { public static void main(String args[]) { JFrame myFrame = new Greeting(); myFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); } }

23 Autumn 2013CE203 Part 623 Using Frames 5 The setDefaultCloseOperation method is used to specify what should happen when the user clicks the close-box of the window containing the frame; this will usually be the termination of the program, as in this example. Other options include DISPOSE_ON_CLOSE, which causes the window to be closed whilst leaving the program running, and DO_NOTHING_ON_CLOSE, which indicates that the click should be ignored.

24 Autumn 2013CE203 Part 624 Using Frames 6 There may be circumstances in which we want to do something more specific when the window is closed – for example if the program has created several frames we may wish to decrement the frame count and terminate only if it has reached zero. In such circumstances it is necessary to add a window listener (which is similar to an action listener) to the frame.

25 Autumn 2013CE203 Part 625 Using Frames 7 In most cases classes that extend JFrame are written for a specific program and not intended for use in other programs. It is often more convenient to write the main method inside the frame class instead of creating a separate class:

26 Autumn 2013CE203 Part 626 Using Frames 8 public class Greeting extends JFrame { public Greeting() { super("Greeting example"); setSize(300, 200); setVisible(true); } public void paint(Graphics g) { // as before } public static void main(String args[]) { JFrame myFrame = new Greeting(); myFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); } }

27 Autumn 2013CE203 Part 627 Using Frames 9 We can add components to the content pane of a JFrame object in the same way as we add them to the content pane of a JApplet object. However, since the JFrame class does not have an init method, the creation of the components must be performed in the constructor. The default layout manager for a frame is, as with applets, BorderLayout. On the next slides there is an outline of a frame-based version of the square-calculating class from part 2. The action listener class, which has been omitted, should be identical to the one seen previously.

28 Autumn 2013CE203 Part 628 Using Frames 10 // Arith.java – frame version import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Arith extends JFrame { JTextField input, result; public static void main(String args[]) { JFrame myFrame = new Arith(); myFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); } // continued on next slide

29 Autumn 2013CE203 Part 629 Using Frames 11 public Arith() { super("Squares of numbers"); input = new JTextField(5); input.addActionListener(……); result = new JTextField(25); result.setEditable(false); setLayout(new FlowLayout()); add(new JLabel( "Type a number and press return")); add(input); add(result); setSize(300, 200); setVisible(true); } }

30 Autumn 2013CE203 Part 630 Text Areas 1 The JTextArea class permits the display and manipulation of multiple lines of text. This class has a constructor with two arguments indicating the number of visible rows and columns – to create a text area whose visible area comprises 12 rows of 20 characters we could use JTextArea myTextArea = new JTextArea(12,20); When this two-argument constructor is used the area will initially contain no text.

31 Autumn 2013CE203 Part 631 Text Areas 2 There is also a constructor that takes as an argument a string indicating the initial contents. The number of visible rows and columns will be determined by the number of lines of text in the string and the length of the longest line. A third constructor is available – this takes a string and two integers, allowing the specification of both the initial contents and the number of visible rows and columns: JTextArea myTextArea2 = new JTextArea( "This is the first line\n"+ "and this is the second line", 5,30);

32 Autumn 2013CE203 Part 632 Text Areas 3 The contents of a JTextArea object may be changed using the setText method: myTextArea.setText("line 1"); Additional text may be added to the end of the contents using the append method: myTextArea.append("\nline 2"); The class has a setEditable method similar to that of the JTextField class; if this is not used the area is by default editable.

33 Autumn 2013CE203 Part 633 Text Areas 4 It is not possible to add an action listener to a text area; text input by a user would normally be processed in a button- handler which examines the contents of the text area using the getText method. A user may use the mouse to select part of the contents of a text area; there is a method called getSelectedText that returns the contents of the currently-selected part of the area. We could use this in a statement such as myTextArea2.setText( myTextArea1.getSelectedText());

34 Autumn 2013CE203 Part 634 Text Areas 5 If a line of text in a text area is too long to be displayed in the visible area only part of the line will be visible. The user can however see the rest of the line by using the cursor keys. However it is sometimes preferable to make the whole width of the text visible by using line wrapping, i.e. the display of a long line is continued on the next line of the text area. To enable this, the setLineWrap method should be used. myTextArea.setLineWrap(true);

35 Autumn 2013CE203 Part 635 Text Areas 6 Line wrapping will by default break the line after the last visible column, resulting in words being split across two lines. To enforce the break to occur between words it is necessary to use myTextArea.setWrapStyleWord(true); The use of cursor keys to allow the non-visible parts of a text area to be seen is not always convenient – if the visible area is small in comparison to the size of the text the user may need to press a cursor key many times or hold it down and risk going too far. Scroll bars provide a more user-friendly way of navigating text areas.

36 Autumn 2013CE203 Part 636 Scroll Panes 1 The simplest way of providing scroll bars for a text area is to place the area inside a scroll pane. To do this we must create a JScrollPane object and add this to a container instead of adding the text area directly. A scroll pane may contain any object of a class that implements the Scrollable interface. The only classes we have seen that implement this interface are JTextField and JTextArea.

37 Autumn 2013CE203 Part 637 Scroll Panes 2 The scrollable component to be placed in a scroll pane is usually supplied as an argument to the constructor, e.g. add(new JScrollPane(myTextArea), BorderLayout.CENTER); The default behaviour of a scroll pane is to provide scroll bars only when needed, i.e. when the number of rows or columns of text exceeds the visible size. This policy may be overridden by defining specific policies for horizontal and/or vertical scroll bars.

38 Autumn 2013CE203 Part 638 Scroll Panes 3 Scroll-bar policies may be specified as arguments to the JScrollPane constructor – if this is done both policies must be specified explicitly even if only one differs from the default. To provide a vertical scroll bar but no horizontal scroll bar we would use add(new JScrollPane(myTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER)); If a scroll bar should be displayed only when needed, we would use VERTICAL_SCROLLBAR_AS_NEEDED or HORIZONTAL_SCROLLBAR_AS_NEEDED

39 Autumn 2013CE203 Part 639 Graphics Methods 1 We have already encountered the drawString, setColor, drawRect and fillRect methods from the Graphics class; these are normally used in paint and paintComponent methods, which take an argument of type Graphics. The drawLine method can be used to draw a line; this method has four arguments, the x and y coordinates of each end of the line, so, for example, g.drawLine(0,10,30,40); will draw a line from (0,10) to (30,40).

40 Autumn 2013CE203 Part 640 Graphics Methods 2 The clearRect method is similar to fillRect but draws the rectangle in the background colour (effectively erasing anything that was displayed in the area specified by the arguments). The methods drawOval and fillOval produce an oval instead of a rectangle. These methods take the same four arguments as drawRect (the x- and y-coordinates of the top corner left and the width and height) and draw an oval that it is enclosed by the rectangle specified by the arguments, touching the rectangle at the centre of each side. If the rectangle is a square, the oval will of course be a circle.

41 Autumn 2013CE203 Part 641 Graphics Methods 3 To draw a circle with centre coordinates (x,y) and radius r we can calculate that the coordinates of the top left-hand corner of the enclosing rectangle will be (x-r,y-r) and the width and height of the rectangle will be the diameter of the circle (i.e. twice the radius. Hence we would use g.drawOval(x-r,y-r,2*r,2*r);

42 Autumn 2013CE203 Part 642 Graphics Methods 4 The drawRoundRect and fillRoundRect methods produce rectangles with rounded corners; they have six arguments: the first four are the same as the arguments of drawRect, and the last two are used to indicate the width and height of the imaginary oval that would be produced by combining the four arcs at the corners.

43 Autumn 2013CE203 Part 643 Graphics Methods 5 The drawArc and fillArc methods produce a portion of an oval (an outline or a segment); they also have six arguments: the first four are the same as those of drawOval, the fifth indicates the starting position of the arc by specifying the angle in degrees (see the diagram on the next slide), and the sixth indicates the number of degrees through which the arc extends (positive numbers indicating anticlockwise and negative numbers indicating clockwise).

44 Autumn 2013CE203 Part 6 44 Graphics Methods 6 The segment shown below would be produced by g.fillArc(10,10,300,200,10,40 );

45 Autumn 2013CE203 Part 645 Graphics Methods 7 The drawPolygon and fillPolygon methods can be used to produce polygons: each takes three arguments: two int arrays containing the x- and y-coordinates respectively of the corners and an int indicating the number of corners. For example we could use the following program fragment to draw a solid triangle with corners at (10,10), (90,70) and (30,110). int[] xCoords = { 10, 90, 30 }; int[] yCoords = { 10, 70, 110 }; g.fillPolygon(xCoords, yCoords, 3);

46 Autumn 2013CE203 Part 646 Graphics Methods 8 If the third argument supplied to drawPolygon or fillPolygon is smaller than the size of the arrays only part of each of the arrays will be used. This allows the same arrays to be reused to draw polygons with different numbers of sides. If the size of either of the arrays is smaller than the third argument an exception will be thrown. There is also a method drawPolyline which does not connect the last co-ordinate pair from the arrays with the first pair (i.e. it draws an incomplete polygon).

47 Autumn 2013CE203 Part 647 Graphics Methods 9 There are also drawPolygon and fillPolygon methods with an argument of type Polygon ; this is useful if we wish to store information about polygons before they are drawn. The Polygon class has a constructor that takes three arguments similar to those of drawPolygon. There is also a no-argument constructor that allows us to add coordinates to a polygon one at a time using the addPoint method: Polygon p = new Polygon(); p.addPoint(10, 10); p.addPoint(90, 70); p.addPoint(30, 110); g.drawPolygon(p);


Download ppt "CE203 - Application Programming Autumn 2013CE203 Part 61 Part 6."

Similar presentations


Ads by Google