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

Slides:



Advertisements
Similar presentations
Applets and Graphics.
Advertisements

Chapter 16 GUI Programming Basics GUI Overview Event-Driven Programming Basics GUI Classes and Packages A Simple Window Program JFrame Class Java Components.
User Interfaces II GUI – Awt, Swing, Web
Chapter 15 Graphics. To paint, you need to specify where to paint. Each component has its own coordinate system with the origin (0, 0) at the upper-left.
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
CE203 - Application Programming Autumn 2013CE203 Part 11 Part 1.
Graphical User Interfaces
Made with love, by Zachary Langley Applets The Graphics Presentation.
Web Design & Development Lecture 19. Java Graphics 2.
Frame Windows A frame object is used to create a graphical frame window. This frame is used to show information in a graphical application. The JFrame.
CSE 1341 Honors Professor Mark Fontenot Southern Methodist University Note Set 21.
Graphics and event-driven programs Learning objectives By the end of this lecture you should be able to: identify and use some of the common components.
Basic Java – Interface design. Understand: How to use TextPad for Java How to define classes and objects How to create a GUI interface How event-driven.
Java Software Development Paradigm Lecture # 12. Basics of GUI.
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
Graphics Chapter 16.  If you want to draw shapes such as a bar chart, a clock, or a stop sign, how do you do it?
PHY-102 SAPIntroductory GraphicsSlide 1 Introductory Graphics In this section we will learn how about how to draw graphics on the screen in Java:  Drawing.
Graphics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Graphical User Interface Bonus slides Interaction Between Components & Drawing.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Java Graphics Section 1 - Multi-File Graphics Programs Section 2 - The Coordinate System and Graphics Context g Section 3 - The Java Drawing and Painting.
GUI and Swing, part 2 The illustrated edition. Scroll bars As we have previously seen, a JTextArea has a fixed size, but the amount of text that can be.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
1 Applets Chapter 1 To understand:  why applets are used to extend the capabilities of Web pages  how an applet is executed and know about the restrictions.
Chapter 121 Window Interfaces Using Swing Chapter 12.
© The McGraw-Hill Companies, 2006 Chapter 10 Graphics and event- driven programs.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
Java Programming Chapter 10 Graphical User Interfaces.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 20.1 Test-Driving the Screen Saver Application.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
2-Dec-15 Inner Classes. 2 Inner classes All the classes so far have been “top level” It is possible (and useful) to define a class inside another class.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Basics of GUI Programming Chapter 11 and Chapter 22.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Java Programming, Second Edition Chapter Thirteen Understanding Swing Components.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 4 – Completing the Inventory Application.
 Many event-listener interfaces contain multiple methods.  An adapter class implements an interface and provides a default implementation (with an empty.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Graphical User Interface (GUI)
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Inner Classes.
Inner Classes 27-Dec-17.
A First Look at GUI Applications
Graphical User Interface (pronounced "gooey")
Java Programming: Guided Learning with Early Objects
4.14 GUI and Graphics Case Study: Creating Simple Drawings (Cont.)
Inner Classes 17-Apr-19.
Inner Classes 21-Apr-19.
Inner Classes 11-May-19.
Inner Classes 18-May-19.
Graphical User Interface
Inner Classes 25-Oct-19.
Presentation transcript:

CE203 - Application Programming Autumn 2013CE203 Part 61 Part 6

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.

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

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

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.

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

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

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 }

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() { …… } } }

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

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

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.

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

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

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.

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.

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

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

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

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

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.

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

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.

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.

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:

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

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.

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

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

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.

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

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.

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

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

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.

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.

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.

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

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

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.

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

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.

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

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

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

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

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