CS100A, Lecture 16, 27 October 1998 1 CS100A Lecture 16 27 October 1998 Assignment 7: A Checker-playing program: learning about GUIs and working with a.

Slides:



Advertisements
Similar presentations
Chapter 18 Building the user interface. This chapter discusses n Javas graphical user interface. n Swing: an enhancement of a library called the Abstract.
Advertisements

Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
Chapter 5 Programming Graphics. Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such.
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.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Applets What is an Applet? Applet Parameters Graphics in Applets Other Applet.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
June 1, 2000 Object Oriented Programming in Java (95-707) Advanced Topics 1 Lecture 9 Object Oriented Programming in Java Advanced Topics Abstract Windowing.
Java Programming, 3e Concepts and Techniques Chapter 5 Arrays, Loops, and Layout Managers Using External Classes.
18-Jun-15 Applets. 2 An applet is a program that is typically embedded in a Web page and can be run from a browser You need special HTML in the Web page.
26-Jun-15 Applets. 2 An applet is a Panel that allows interaction with a Java program A applet is typically embedded in a Web page and can be run from.
Lecture 241 CS110 Lecture 25 Tuesday, May 4, 2004 Announcements –final exam Thursday, May 20, 8:00 AM McCormack, Floor 01, Room 0608 (easier than last.
© 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 Programs u 1 project file –with an extension of.mcp –contains information that CodeWarrior needs to run the program u >= 1 source files –have an extension.
Adding Controls to User Forms. Adding Controls A user form isn’t much use without some controls We’re going to add controls and write code for them Note.
Chapter 5 - Making Music: An On-Screen Piano
Applets, AWTS CompSci 230 Software Construction.
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 16: Java Applets & AWT Fundamentals of Web Programming.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
Java: Chapter 1 Computer Systems Computer Programming II.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Learn about the types of Graphics that are available Develop a basic Graphics applet Develop a basic Graphics application Review the Java API and use.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
Lab 6: Shapes & Picture Extended Ellipse & Rectangle Classes Stand-Alone GUI Applications.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
CSTP FS99CS423 (cotter)1 Java Graphics java.awt.*;
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Program that runs in appletviewer (test utility for applets) Web browser (IE, Communicator) Executes when HTML (Hypertext Markup Language) document containing.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
CS100A, Fall Lecture, 4 Nov. 1 CS100A, Fall 1997 Lecture 4 November: OTHELLO Goals: Introduce you to assignment 8. Let you have fun with the game.
1 Lesson: Applets with User Input and Output with GUI ICS4M.
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.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT features include: a rich set of user interface components; a.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
1 Lecture 25 Listening to buttons and mice Quotes by Tony Hoare There are two ways of constructing a software design: (1) make it so simple that there.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Types and Interfaces COMP.
CSI 3125, Preliminaries, page 1 AWT. CSI 3125, Preliminaries, page 2 AWT Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based.
Creating a GUI Class An example of class design using inheritance and interfaces.
Lecture 33: More Graphical User Interface (GUI) Announcements & Review Read Ch GU1 & GU2 Cohoon & Davidson Ch 14 Reges & Stepp Lab 10 set game due 4/26.
Lecture # 6 Graphical User Interface(GUI). Introduction A graphical user interface (GUI) presents a user- friendly mechanism for interacting with an application.
Graphical User Interface (GUI) Two-Dimensional Graphical Shapes.
1 Java and AWT CPS 470 Spring 1998 Laura Campbell.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Getting Started with GUI Programming Chapter 10 CSCI 1302.
10/20/2005week71 Graphics, mouse and mouse motion events, KeyEvent Agenda Classes in AWT for graphics Example java programs –Graphics –Mouse events –Mouse.
CSC 205 Programming II Lecture 5 AWT - I.
Welcome To java
Java Swing.
Abstract Window ToolKit (AWT)
Ellen Walker Hiram College
Chap 7. Building Java Graphical User Interfaces
Introduction to Computing Using Java
AWT Components and Containers
GUI building with the AWT
Presentation transcript:

CS100A, Lecture 16, 27 October CS100A Lecture October 1998 Assignment 7: A Checker-playing program: learning about GUIs and working with a well-designed and well- documented program GUI: Graphical User Interface Project designed to show advantage of “object-oriented programming”. The awt (abstract window toolkit) contains many classes --and subclasses-- and extending some of them is an integral part of implementing a GUI. This project will NOT require you to write code that deals with the GUI; the assignment gives you only an introduction to the topic. Your programming will deal with the code that manipulates the checkers represented in a two-dimensional array. And a lot of it requires only calling already-written methods.

CS100A, Lecture 16, 27 October Some classes in the abstract window toolkit class Frame: An instance is a “window” on the screen. It can contain “components”. You get to say where the components go. Frame is a subclass of Window Window is a subclass of Container Containeris a subclass of Component Some components that can appear in a Frame instance of Button: a button to be clicked with mouse. instance of Label: a String that the user can’t change. instance of TextField: a string that the user can change instance of TextArea:2-dimensional text area, changeable instance of Canvas: Can be drawn on using Graphics class Event: An instance describes some event, like “mouse up”, “mouse drag”, “click on a button”, “click on the window-destroy field”, a keystroke.

CS100A, Lecture 16, 27 October (part of) class Frame public class java.awt.Frame extends java.awt.Window implements java.awt.MenuContainer { // possible cursor types for method setCursor public final static int CROSSHAIR_CURSOR; §§ public final static int DEFAULT_CURSOR; public final static int HAND_CURSOR;... public Frame(String title); public void dispose(); public String getTitle(); public void setTitle(String title); public boolean isResizable(); public void setResizable(boolean resizable); public int getCursorType(); public void setCursor(int cursorType);

CS100A, Lecture 16, 27 October part of class Window (superclass of Frame) public class java.awt.Window extends java.awt.Container { //Constructor public Window(Frame parent); // Remove, get rid of, this window public void dispose ( ); // Lay out the components in window with preferred size public void pack( ); // Make this window visible public void show( ); // Put window behind other windows public void toBack( ); // Put window in front of other windows public void toFront ();

CS100A, Lecture 16, 27 October part of class Container (superclass of Window) public class java.awt.Container extends java.awt.Component { // Add component comp to the container public Component add(Component comp); // remove comp from the container public void remove(Component comp); // Tell container what layout manager to use public void setLayout(LayoutManager mgr); // Lay out the components in container with // preferred size public void pack( );

CS100A, Lecture 16, 27 October part of class Component (superclass of Component) public class java.awt.Component { // Process action, return “action has been handled” public boolean action(Event evt, Object what); // Handle event, return “event has been handled” public boolean handleEvent(Event evt); // Make component insensitive (sensitive) to use input public void disable( ); public void enable( ); // repaint this component public void repaint( ); // Change the width and height to w and h public void resize(int w, int h); // Set the background color to c public void setBackground(Color c); // Make sure the component is seen on the screen public void show( );

CS100A, Lecture 16, 27 October Layout Manager Used to place and control components on a Frame. Several layout managers --simple ones give programmer less control, the more complex ones give more There are also programs that help you build GUIs without having to do all the programming. Look briefly at one layout manager, GridBagLayout. Requires an instance of another class, GridBagConstraints. Basically, to add a new component to the Frame, you set the properties you want it to have in the instance of GridBagConstraints and then call a method add.

CS100A, Lecture 16, 27 October GridBagLayout and GridBagConstraints AAAAA BBBB CCCCCCCCCCC A: TextField B: Button C: TextArea A frame with a TextField, a Button, and a TextArea gbl= new GridBagLayout(); gbc= new GridBagConstraints(); setLayout(gbl); TextField tf= new TextField(“a text field”); TextArea ta= new TextArea(“text\narea”); Button b= new Button(“name on button”); add(tf,gbl,gbc, 0,0, 3,1, 100,100); add(ta,gbl,gbc, 1,1, 2,2, 100,100); add(tf,gbl,gbc, 3,2, 5,3, 100,100);

CS100A, Lecture 16, 27 October Following slides: class Experiment, which is an extension of Frame. It has several components in the frame. class TrivialApplication, which defines a variable that can contain an Experiment. class CheckersSquare (stripped down version), a component of class Canvas. We spend some time demonstrating and investigating these classes. You can download these three classes in a single file from our web site (look for “assignment 7”). Start a new codewarrior project, using the Java application stationery (not the CUCS stationery). Then replace file TrivialApplication.java with this file (of the same name).

CS100A, Lecture 16, 27 October // Frame to illustrate the awt. public class Experiment extends Frame { // Components that go in the frame CheckersSquare sq; Label lab; TextField textf; TextArea texta; // Titles for buttons String[ ] bs= {"new game", "quit"}; // The layout and constraint variables for this frame GridBagLayout gbl; GridBagConstraints gbc; final int xw= 100; // Weights for all the components final int yw= 100; // when they are resized (class Experiment to be continued)

CS100A, Lecture 16, 27 October // Constructor: a frame with various components public Experiment() { super("Experiment"); gbl= new GridBagLayout(); gbc= new GridBagConstraints(); setFont(new Font("Dialog", Font.PLAIN, 10)); setLayout(gbl); gbc.fill= gbc.BOTH; sq= new CheckersSquare(0,0); add(sq,gbl,gbc,0,0,1,1,xwt,yw); gbc.fill= gbc.BOTH; lab= new Label("A label at (1,1)"); add(lab, gbl,gbc,1,1,1,1,xw,yw); textf= new TextField("A TextField at (1,2)"); add(textf,gbl,gbc,1,2,1,1,xw,yw); texta= new TextArea("A TextArea\nat (1,3)"); add(texta,gbl,gbc,1,3,1,1,xw,yw); add(new Button(bs[0]),gbl,gbc, 2,0, 1,1, xw,yw); add(new Button(bs[1]),gbl,gbc, 3,0, 1,1, xw,yw); pack( ); move(150,50); show(); setResizable(false); }

CS100A, Lecture 16, 27 October // Add component c to gbl with constraints gbc at position // (x,y). Component c takes w columns and r rows, and is // weighted (wx, wy). private void add(Component c, GridBagLayout gbl, GridBagConstraints gbc, int x, int y, int w, int h, int wx, int wy) {gbc.gridx= x; gbc.gridy= y; gbc.gridwidth= w; gbc.gridheight= h; gbc.weightx= wx; gbc.weighty= wy; gbl.setConstraints(c, gbc); add(c); } (class Experiment to be continued)

CS100A, Lecture 16, 27 October // If button was pressed, process it; otherwise, let method // action in the superclass process it public boolean action(Event e, Object arg) { if (arg.equals(buttons[0])) { // Handle press of "New game" and return true System.out.println("\"new game\" pressed"); return true;} if (arg.equals(buttons[1])) { // Handle press of "Quit" and return true System.out.println("\"Quit\" pressed"); System.out.println("TextField is: \"" + textf.getText( ) + "\""); System.out.println("selection is: \"" + textf.getSelectedText( ) + "\""); return true; } return super.action(e,arg); } (class Experiment to be continued)

CS100A, Lecture 16, 27 October // Process press of WINDOW_DESTROY or mouse up // in a CheckersSquare public boolean handleEvent(Event e) { //System.out.println("" + e); if (e.id == Event.WINDOW_DESTROY) { System.out.println("Window destroy clicked"); //dispose(); return true; } if (e.id == Event.MOUSE_UP && e.target instanceof CheckersSquare) { System.out.println("Mouse up in a” + “CheckersSquare"); return true; } if (e.id == Event.MOUSE_MOVE) { System.out.println("Mouse move"); return true; } return super.handleEvent(e); } (End of class Experiment)

CS100A, Lecture 16, 27 October public class TrivialApplication { public static void main(String args[]) { System.out.println( "Hello World!" ); Experiment f= new Experiment(); } // A square of the game Checkers public class CheckersSquare extends Canvas { static public final int EMPTY= 0; static public final int RED= 1; static public final int BLACK= 2; Rectangle b; // Containing rectangle of this square int col; int row;// col, row no. of this square on board private int fill= EMPTY; // Constructor: An initially empty square that belongs in // column c, row r of the board public CheckersSquare(int c, int r) { super(); col= c; row= r; if ((c+r)%2 == 1) setBackground(color.gray); else setBackground(color.pink); resize(42,42); b= bounds(); repaint();} (to be continued)

CS100A, Lecture 16, 27 October (continuation of CheckersSquare) // Constructor: An initially empty square that belongs in // column c, row r of the board public CheckersSquare(int c, int r) { super(); col= c; row= r; if ((c+r)%2 == 1) setBackground(color.gray); else setBackground(color.pink); resize(42,42); b= bounds(); repaint(); } // Paint square (with its piece, if any), using Graphics g public void paint (Graphics g) { Color save= g.getColor( ); if (fill==RED) g.setColor(Color.red); else g.setColor(Color.black); g.fillOval(b.x+b.width/5, b.y+b.width/5, b.width/2, b.height/2); g.setColor(save); } (end of class CheckersSquare)

CS100A, Lecture 16, 27 October EVENTS Event: something like mouse down, mouse drag, click on a button, pressing a key down, letting a key up, and clicking on the “window-destroy” box. An event represented by an instance of class Event. Java 1.0 event handling is different from Java 1.1 event handling. We discuss Java 1.0 event handling. When an event happens, one of two methods is called: // Handle button click --return “click processed” public boolean action(Event e, Object arg) {Similar to body of handleEvent} // Handle all other events --return “event handled” public boolean handleEvent(Event e) { if (event can be handled) { Process event; return true; } return super.handleEvent(e); }

CS100A, Lecture 16, 27 October The game of checkers To play the game using a finished program, execute the applet on the CS100A home page (look for assignment 7). For this assignment, download files as instructed on the handout for the assignment. You get a copy of the completed program with parts removed, and you have to fill them in. You will not have to write code that manipulates the GUI, but you are encouraged to study the GUI code! Class Checkers is a subclass of Frame, so an instance is a window on the monitor. Class CheckersSquare is a subclass of Canvas, so an instance is a component on which one can draw ovals and such. An 8x8 array of elements of Class CheckersSquare forms the checker board. Class IntLabel is used to encode two different representations of a number: Int and Label.

CS100A, Lecture 16, 27 October Class CheckersSquare Each square of the checkerboard is an instance of CheckersSquare. Field fill is the piece on this square Fields row, col contain the square’s row, col number Field toBeMoved: = “The piece should be highlighted” Method paint is called by the system whenever the square should be repainted. Repainging can also be requested by a method of this class by calling method repaint. Class CheckersSquare contains a bunch of methods that you should use in writing your code. Spend several minutes familiarizing yourself with them before doing any coding.

CS100A, Lecture 16, 27 October Class Checkers Fields for checker game (not GUI) // Number of red pieces and black pieces on the board IntLabel redCount= new IntLabel(0, reds); IntLabel blackCount= new IntLabel(0, blacks); // clickflag describes clicks made by the user // = 0: No piece has been chosen (clicked on). For all //squares, field toBeMoved is false. // = 1: click was made on a piece of color colorToPlay // oldSq is the square of the piece to be moved; it’s //the only highlighted square int clickflag = 0; CheckersSquare oldSq; int colorToPlay; // player (i.e. color) to place next int otherColor;// the other color Your changes are restricted to five methods, but before you make the changes, study carefully at all the other methods in class Checkers. // Set the board up for a new game public void newGame( )

CS100A, Lecture 16, 27 October // Move piece from oldSq to newSq and return true. If // move is not possible, do nothing and return false. private boolean validMove(CheckersSquare oldSq, CheckersSquare newSq) // Return "move oldSq to newSq is valid non-jump // move for player colorToPlay". Assume oldSq contains // a piece of colorToPlay and newSq is empty black square private boolean isValidNonjump(CheckersSquare oldSq, CheckersSquare newSq) // Return "move oldSq to newSq is valid jump for player // colorToPlay". Assume oldSq contains piece and that // newSq is an empty black square private boolean isValidjump(CheckersSquare oldSq, CheckersSquare newSq) // clickflag=1. If pieces on oldSq and newSq have same // color, switch to moving the piece on newSq. Otherwise // try to move piece from oldSq to square newSq. If not // possible, give error message; if possible, do it and // switch players public void processClickTwo(CheckersSquare newSq)