CS 201 Advanced Object-Oriented Programming Lab 1 - Improving Your Image Due: Feb. 3/4, 11:30 PM

Similar documents
CS 315 Software Design Homework 1 First Sip of Java Due: Sept. 10, 11:30 PM

CS 201 Advanced Object-Oriented Programming Lab 10 - Recursion Due: April 21/22, 11:30 PM

Assignment 2. Application Development

CSCI 053. Week 5 Java is like Alice not based on Joel Adams you may want to take notes. Rhys Price Jones. Introduction to Software Development

CIS 162 Project 1 Business Card Section 04 (Kurmas)

TWO-DIMENSIONAL FIGURES

Dr. Hikmat A. M. AbdelJaber

CS 201 Advanced Object-Oriented Programming Lab 3, Asteroids Part 1 Due: February 17/18, 11:30 PM

CS Problem Solving and Object-Oriented Programming

Chapter 7 Applets. Answers

Graphics in Swing. Engineering 5895 Faculty of Engineering & Applied Science Memorial University of Newfoundland

Graphic User Interfaces. - GUI concepts - Swing - AWT

CS Programming Exercise:

G51PRG: Introduction to Programming Second semester Applets and graphics

The Fundamentals. Document Basics

PIC 20A GUI with swing

CS 134 Programming Exercise 2:

ICOM 4015 Advanced Programming Laboratory. Chapter 3 Introduction to Graphical Applications in Java using Swing

InDesign Part II. Create a Library by selecting File, New, Library. Save the library with a unique file name.

Name CS/120 Sample Exam #1 -- Riley. a) Every program has syntax, which refers to the form of the code, and, which refers to the meaning of the code.

Working with PDF s. To open a recent file on the Start screen, double click on the file name.

Class 14: Introduction to the Swing Toolkit

1.00 Lecture 14. Lecture Preview

Assignment 1. Application Development

public static void main(string[] args) { GTest mywindow = new GTest(); // Title This program creates the following window and makes it visible:

AP CS Unit 12: Drawing and Mouse Events

HOW TO. In this section, you will find. miscellaneous handouts that explain. HOW TO do various things.

Creating Interactive PDF Forms

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

CS 201 Advanced Object-Oriented Programming Lab 6 - Sudoku, Part 2 Due: March 10/11, 11:30 PM


On the Web sun.com/aboutsun/comm_invest STAROFFICE 8 DRAW

End User Guide. 2.1 Getting Started Toolbar Right-click Contextual Menu Navigation Panels... 2

CP122 Computer Science I. Chapter 2: Using Objects

Graphics and Painting

Using the API: Introductory Graphics Java Programming 1 Lesson 8

Control Statements: Part Pearson Education, Inc. All rights reserved.

Create and edit word processing. Pages.

PowerPoint Slide Basics. Introduction

Topic 8 Graphics. Margaret Hamilton

InDesign Tools Overview

Programming Project 1

HTML Exercise 21 Making Simple Rectangular Buttons

ICOM 4015 Advanced Programming Laboratory. Chapter 1 Introduction to Eclipse, Java and JUnit

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

CS 2110 Fall Instructions. 1 Installing the code. Homework 4 Paint Program. 0.1 Grading, Partners, Academic Integrity, Help

Eclipse Setup. Opening Eclipse. Setting Up Eclipse for CS15

Using Graphics. Building Java Programs Supplement 3G

Agenda. Programming Seminar. By: dr. Amal Khalifa. Coordinate systems Colors Fonts Drawing shapes Graphics2D API

PowerPoint Basics (Office 2000 PC Version)

Ancient Cell Phone Tracing an Object and Drawing with Layers

Chapter 1 Introducing Draw

Creating a Flyer. Open Microsoft Publisher. You will see the list of Popular Publication Types. Click the Blank Page Sizes.

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

MICROSOFT WORD XP INTERMEDIATE

Using Microsoft Word. Working With Objects

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

2IS45 Programming

Part 1: Basics. Page Sorter:

CSCI 161: Introduction to Programming I Lab 1b: Hello, World (Eclipse, Java)

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

CSE wi Final Exam 3/12/18. Name UW ID#

Program and Graphical User Interface Design

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Submit your solution to the Desire2Learn drop box. You may submit as many versions as you like the last one will be graded.

Learning to use the drawing tools

How to lay out a web page with CSS

9. APPLETS AND APPLICATIONS

INFORMATION TECHNOLOGY

DeskTop Publishing on Linux

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

ITP 101 Project 2 - Photoshop

CPM-200 User Guide For Lighthouse for MAX

Visual C# Program: Simple Game 3

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

PowerPoint 2016 Building a Presentation

Building Java Programs

Image Java Foundation Classes (JFC) java.awt.image JFC. Image. Image. Image PNG GIF JPEG

Faculty Development Seminar Series Constructing Posters in PowerPoint 2003 Using a Template

CMPSCI 120 Extra Credit #1 Professor William T. Verts

HYPERSTUDIO TOOLS. THE GRAPHIC TOOL Use this tool to select graphics to edit. SPRAY PAINT CAN Scatter lots of tiny dots with this tool.

Graphics JFrame. import java.awt.*; import javax.swing.*; public class XXX extends JFrame { public XXX() { ... main() public static

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Excel Basics Fall 2016

Figure 1 Forms category in the Insert panel. You set up a form by inserting it and configuring options through the Properties panel.

Contents. Introducing Clicker Paint 5. Getting Started 7. Using The Tools 10. Using Sticky Points 15. Free resources at LearningGrids.

User interfaces and Swing

EXCEL BASICS: MICROSOFT OFFICE 2010

Introduction to Microsoft Word 2008

PowerPoint Launching PowerPointX

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

PowerPoint 2003: Basic Instructor s Edition

More about GUIs GEEN163

DOING MORE WITH WORD: MICROSOFT OFFICE 2007

How to...create a Video VBOX Gauge in Inkscape. So you want to create your own gauge? How about a transparent background for those text elements?

Topic 8 graphics. -mgrimes, Graphics problem report 134

In the first class, you'll learn how to create a simple single-view app, following a 3-step process:

Transcription:

CS 201 Advanced Object-Oriented Programming Lab 1 - Improving Your Image Due: Feb. 3/4, 11:30 PM Objectives The objectives of this assignment are: to refresh your Java programming to become familiar with Eclipse Assignment Your program should provide an ID card display that looks as follows: You do not need to follow this exact layout but your display should exhibit the following characteristics: It should include an image It should include some text It should include some shapes (ovals, rectangles and lines are the basic drawing capabilities that Java provides). It should use a few colors. The window should be the right size to display the information comfortably without seeming too large.

Program Design The design of your program should be similar to the HelloFromVenus program that we looked at in class and that appears at the end of this handout. In particular, your program should contain two classes, IDCardDisplay and IDCard. The IDCardDisplay class should extend JComponent. The main method of this class should construct a JFrame, call the IDCardDisplay constructor, place the constructed instance of IDCardDisplay in the JFrame and then display the JFrame. IDCardDisplay should also contain a paintcomponent method that draws the id card. The IDCard class should be able to draw id cards that have different pictures, names or messages. It should have a constructor that takes these 3 pieces of information as parameters and saves them in instance variables. It should also contain a paint method that does the actual drawing. IDCard s paint method should be called from IDCardDisplay s paint- Component method. Read on for more details on how to do this. Getting Started with Eclipse The Basics We will use Eclipse in this class. Eclipse is available on all major platforms: Linux, Windows and Mac. You can download Eclipse for your own personal computer for free from http://www.eclipse.org/downloads/. There are many versions. You should download the one that says Eclipse IDE for Java Developers. Eclipse has become one of the most widely used software development environments in recent years for Java programming. To start Eclipse on the Macs in 307, click on the Eclipse icon in the dock (at the bottom of the screen). Eclipse maintains all your code in a workspace. The workspace contains a collection of projects, where each project typically corresponds to a single program. When you first start Eclipse, you need to tell it where the workspace should be. Be sure to select a location in your account. Create a folder for the workspace, called workspace or cs201workspace or something similar. All of your projects this semester will be done in this workspace. Next, you will see a screen like the one below. Select the arrow icon on the right middle side of the window that says Go to Workbench. The display will change to show the Eclipse workspace as shown below. The Eclipse window has a package explorer panel on the left where the names of your projects and classes will be displayed, and a Problems panel at the bottom where error messages (and other informational messages) will be displayed. The main area in the top middle is where your code will appear. You can close the Task List and the Outline panels on the right side by clicking on their icons since they are not so useful for the small projects we will be doing this semester. This will give more space to the 2

editing panel. There is a lot of functionality to Eclipse, so it may take some time to master it, but the basics are mostly intuitive. We will first customize Eclipse so that it has the preference settings most useful for this course. Go to the schedule page of the course website and right-click on the link for today s lab that says Eclipse Preference File. Save the link in a file. Then, inside Eclipse, open the File menu, select Import, click the triangle next to General, then select Preferences. Click the Next button. You should now see a window titled Import Preferences. Click the Browse button and navigate to the Eclipse Preferences file you just saved. Make sure Import all is checked. Click Finish. 3

Create a project called IDCard. To do this, open the File menu. Select New and then Java Project. Enter IDCard for the project name and click Finish. For this program, you will need two classes. ID- CardDisplay will be the main class. To create it, click on the icon in the top toolbar that is a C in a green circle. Make sure the source folder is IDCard/src. Enter IDCardDisplay for the name and click Finish. This will create the stub for a new class named IDCardDisplay. Your Eclipse window should now look like what is shown below. One feature of Eclipse is that it checks your code as you enter it. When it finds an error, an icon will appear in the left margin of the code area. The icon will either be a red X or a red X with a light bulb. In either case, an error message will appear in the bottom panel. If a light bulb is present and you single-click on the light bulb, Eclipse will offer some suggestions on how to correct the error. Often it has the solution in its list; you can then double-click on the solution to have Eclipse perform the necessary edits for you. Take your time when Eclipse reports errors. First, errors often occur simply because you are in the middle of doing something and these errors go away when you complete the task. So, 4

it is generally a good idea to ignore the warnings that come up while you are editing. Second, read the messages carefully. They often have good advice. (But not always Computers are not actually very smart) Third, before selecting a change to be applied automatically, make sure you understand Eclipse s suggestion. If you don t understand it, it s probably not the right thing to do Ask for help if you are confused. When you have no red X s, you can run your program. To do this, select your IDCardDisplay class in the Project Explorer and click on the green play arrow in the palette running across the top. You will also want to import an image into your Eclipse project that your program will use. To do this, select the project name in the Project Explorer, open the File menu and select Import. In the window that comes up, select FileSystem from the General list and click Next. Click the Browse button and find and select the folder containing the image file you want to use. This folder name should now appear in the left column in the Import window. Click on the folder name (not on the checkbox to the left of the name). Now the right column should list the files in that folder. Find the file you want and select its checkbox. Then click Finish. Be sure that the image is inside your project, but not inside the src folder. Some helpful commands Over the course of the semester, we will investigate some of the commands in Eclipse that are very helpful in getting your programming tasks done efficiently. For now, I would like you to get used to using a few of these commands: Format. The source menu contains a command called Format. Please be sure to use this command before submitting your code. It will ensure that your program is indented reasonably. If you use the Format command with some code selected, it will format that code. If there is no code selected, it will format the entire class. Organize imports. This command is also in the Source menu. It arranges your import statements alphabetically and also helps create the import statements for you so that you import individual classes (like java.awt.color) rather than entire packages (like java.awt.*). This is a very simple way for you to eliminate any warning or error messages you may be getting about imported classes. Java Background One of the benefits of working with Java is that every installation of Java comes with a large set of standard libraries. A Java application written for one operating system should work unchanged on any other operating system. In this lab, you will gain familiarity with some classes that Java provides for drawing. 5

In general, when you want to find out information about how to use a specific Java class or method, you should consult the online Java API available at http://docs.oracle.com/javase/6/docs/api/. For this lab, I have tried to give you all the information that you will need about the classes, but you will definitely want to have this URL bookmarked for the future Step 1: Creating a JFrame The type for window in Java is JFrame. So, the first thing you will need to do is create a main method, similar to the one in HelloFromVenus. In it, you should construct a JFrame. Its constructor takes no arguments. After creating the JFrame, you should set its size by calling setsize. The signature of setsize is: public void setsize(int width, int height) This method sizes the window to a particular size giving the desired width and height in pixels. Do not type the line above into your program. Instead, as we did in worksheets in class, you need to add a call to this method in your code. For example, you could call this as: frame.setsize (300, 400); to create a window that is 300 pixels wide and 400 pixels tall, assuming you have a variable named frame whose type is JFrame. Next, make the window visible by calling JFrame s setvisible method, whose signature is: public void setvisible (boolean visible) If true is passed in, the window becomes visible. If false is passed in, the window is removed from the screen. Be sure that the setvisible call is the last line of your main method. Now, run your program. You should see an empty window. Step 2: Displaying an IDCard Let s first create a very basic IDCard class that only displays the name of the person the card is for. Create a new class called IDCard. In it, define an instance variable, called name, to hold the person s name. Also, define a constructor that takes a String parameter and saves it in the name instance variable. Next declare a paint method in your IDCard class as follows: public void paint(graphics g) { g.setcolor(color.black); g.drawstring(this.name, 30, 50); } When called, this will place the value that is in the name variable into your display, with the left edge 30 pixels from the left edge of the window, and 50 pixels from the top. Add the phrase extends JComponent to the declaration of your IDCardDisplay class so that it now reads: public class IDCardDisplay extends JComponent { This will allow the IDCardDisplay object to be added to the window when you are defining the main method as described below. 6

To place something in the window, you will need to construct an instance of your IDCardDisplay class in your main method. In turn, the IDCardDisplay constructor should create an instance of your IDCard class. The main method in IDCardDisplay should add the IDCard- Display instance to the display. Please refer to the HelloFromVenus example to see how to do this. You also need to define a paintcomponent method in the IDCardDisplay class. This should call super.paintcomponent and then call the id card s paint method. Please refer to the HelloFromVenus example to see how to do this. Run your program again. At this point, you should see a window with the name displayed as described above. Please ask for help if you are not getting this result. Step 3: Add more shapes to your ID Card To draw something in your IDCard, you need to add more code to its paint method. The signatures of the methods that you will use to draw shapes and text are these: public void drawline (int x1, int y1, int x2, int y2); public void drawoval (int x, int y, int width, int height); public void drawrect (int x, int y, int width, int height); public void drawstring (String s, int x, int y); public void filloval (int x, int y, int width, int height); public void fillrect (int x, int y, int width, int height); The arguments to drawline are the x and y values of the 2 endpoints of the line. The x & y arguments to the remaining methods identify the x value of the leftmost portion of the shape and the y value of the topmost portion of the shape. The draw methods give a border with the background showing, while the fill methods gives the same shape but with a solid color, blocking the background. Try adding commands to draw a single shape in your paint method and run your program again. After that works, modify paint to complete your ID card (minus the image). Below is more information on drawing that you should find useful. Fonts and Colors When drawing shapes or text, you must set the color and font prior to doing the drawing. You use the methods: public void setfont (Font f); public void setcolor (Color c); You can define a font by calling the font constructor: Font (font-name, font-face, size) such as new Font ("Helvetica", Font.BOLD, 18) For the font face, you can use the values Font.BOLD, Font.ITALIC or Font.PLAIN. For the font name, you can use any font that is available on the Macs in 307, which includes common font names as well as more unusual ones. To find the names of the fonts on the Mac you are using, open the main named Eclipse and select Preferences... Open General, 7

then Appearance in the left column. Select Colors and Fonts. Next, open Basic in the right panel and select one of the Fonts, like Banner Font. Click the Edit button. This will open a window that would allow you to change the font used. Note, you probably do not want to change the font, but you could use this to explore the font names that you would like to use on your ID card. Colors are defined using RGB (Red-Green-Blue). Each value can range from 0 to 255, where 0 means none and 255 means maximal. RGB 0, 0, 0 is black, while 255, 255, 255 is white. From the same Colors and Fonts window as used to find fonts, you can select an entry like Counter color. When you click Edit, a color chooser will come up that you can use to help find the RGB values for interesting colors. You can also find colors by using a tool called DigitalColor Meter. It is used to find out the RGB value of a color currently on the display. Open the Applications folder, and then the Utilities folder to find DigitalColor meter. As you move the mouse around it will show you a magnified view of the portion of the screen where the mouse is and the RGB value of the color currently under the mouse. For example, in the figure on the right, the mouse is in the Eclipse icon in the dock. We see a magnified view of part of the icon, the color directly under the mouse as well as the RGB value of that color. When you find a color you like, type Shift- -C. This will copy the current color in the RGB values so that you can now paste those values into your class you are writing to create a color to use in your program by calling the Color constructor. For example, to use this color in your program, you would call the Color constructor: Color (int red, int green, int blue) like this: Color eclipseblue = new Color (96, 61, 123); You can also look at color tables online to help you select colors, such as the Wikipedia article on Web Colors. Step 4: Add an image to your ID Card Refer to the HelloFromVenus example to see how to read an image from a file and display it. Style Style is very important in software development. Good style and good documentation greatly increases the maintainability of software. As a result, all the good things you have learned about documentation, choosing variable, method, and class names, etc. are important and will be graded. In particular, we will be grading the following: Formatting: Use the Format command in the Source menu to be certain that you have good, consistent indentation. Naming: Names should convey meaning about the thing that they name. Variables and methods should begin with small letters, with the first letter of later words capitalized, like variablename and methodname. All words used in class names should be capitalized, as in ClassName. Constants should be in all capital letters, with _ separating words, as in CONSTANT_NAME. Constants: You should declare static final constants instead of using literals in your program. 8

Scopes: You should use local variables rather than instance variables whenever possible. Comments: Every class, method and instance variable should have a comment preceding it. There should be a blank line before each comment. You should only put comments inside methods when they add explanation about why the code is written as it is. Comments should not simply repeat what the code says. Extra credit There are two extra credit opportunities for this lab. In general, extra credit requires you to do more exploration on your own to determine how to do these steps. They are worth up to 5 points each. Calculating locations for your shapes so that the pieces move around reasonably if the user resizes the window. Scaling the image as the user resizes the window. Hint: to do this, you will need to call getimage on the ImageIcon instance to get an Image object. Then call getscaledinstance on the Image object, passing in the desired size. Then, call setimage on your ImageIcon, passing in the new scaled image. You will need to calculate the desired size based on the window size. See the API for ImageIcon and Image (http://docs.oracle.com/javase/6/docs/api/) to find the signatures of these methods. Grading Comments Style Step 1: Empty window Step 2: A window with some text Step 3: ID Card with text, shapes and colors Step 4: Adding an image Extra credit - calculate where to place things instead of using constants, scale the image 25 points 25 points 5 points 10 points 20 points 15 points 5 points each Turning in your work To turn in your work, create a jar file that contains your source code. From Eclipse, you can create a jar file as follows. Select your project. Open the File menu and select Export. Click on the triangle next to Java to open it. Select Jar file and click Next. Check the box that says export Java source files and resources. Select a name and destination for the jar file. Then click Finish. Submit your assignment using Ella. 9

Hello From Venus Example The HelloFromVenus class. This is the main class. import java.awt.borderlayout; import java.awt.color; import java.awt.container; import java.awt.graphics; import javax.swing.imageicon; import javax.swing.jcomponent; import javax.swing.jframe; /* * Adapted from Xiaoping Jia, Object-Oriented Software Development Using Java, * Addison-Wesley, 2003. * * Minor modifications made by Barbara Lerner, 2010. */ /** * A simple Java application. It displays a text message and an image of the * planet Venus. */ public class HelloFromVenus extends JComponent { // The background color for the window. private static final Color BACKGROUND_COLOR = Color.BLACK; // The file containing the image private static final String IMAGE_FILE = "Venus.gif"; 10

// The message to display. private static final String MESSAGE = "Hello from Venus"; // The color to use for the message. The color is specified in RGB. // Each parameter can range from 0 to 255. private static final Color FONT_COLOR = new Color(255, 215, 0); // Height of the frame private static final int FRAME_HEIGHT = 350; // Width of the frame private static final int FRAME_WIDTH = 300; // The postcard private Postcard venuspostcard; /** * Create the postcard. */ public HelloFromVenus() { ImageIcon image = new ImageIcon(IMAGE_FILE); image.setimageobserver(this); venuspostcard = new Postcard(BACKGROUND_COLOR, FONT_COLOR, MESSAGE, image); } /** * Draw the postcard * * @param g the graphics object to draw on. */ public void paintcomponent(graphics g) { super.paintcomponent(g); // Send the size of the postcard here in case the user resized the // window. venuspostcard.paint(g, getwidth(), getheight()); } /** * Creates the user interface. * @param args None expected. **/ public static void main(string[] args) { // Create the window and set its size. JFrame f = new JFrame(); f.setsize(frame_width, FRAME_HEIGHT); // Exit the application when the user closes the frame. f.setdefaultcloseoperation(jframe.exit_on_close); // Create the panel that will display the image and text HelloFromVenus venuspanel = new HelloFromVenus(); 11

// Add the venus panel to the center of the window Container contentpane = f.getcontentpane(); contentpane.add(venuspanel, BorderLayout.CENTER); // Display the window. f.setvisible(true); } } The Postcard class. This knows how to layout a postcard. import java.awt.color; import java.awt.font; import java.awt.graphics; import javax.swing.imageicon; /** * Draws a postcard. Different instances of this class can use different * colors, images or messages. * * @author Barbara Lerner * @version Jan 21, 2013 * */ public class Postcard { // The upper left corner of the image. private static final int IMAGE_TOP = 60; private static final int IMAGE_LEFT = 20; // The upper left hand corner of the message measured in pixels. private static final int MESSAGE_LEFT = 40; private static final int MESSAGE_TOP = 25; // Font to display the message in. 24 is the font size. private static final Font FONT = new Font("Helvetica", Font.BOLD, 24); // The background color private Color backgroundcolor; // The color to display the message in private Color fontcolor; // The message to display private String message; // The iage to display private ImageIcon image; 12

/** * Creates a new postcard * @param background the background color * @param font the font color * @param msg the message * @param pic the image */ public Postcard (Color background, Color font, String msg, ImageIcon pic) { this.backgroundcolor= background; this.fontcolor = font; this.message = msg; this.image = pic; } /** * Draws the postcard * @param g the graphics object to draw on * @param width the width of the postcard * @param height the height of the postcard */ public void paint(graphics g, int width, int height) { // Color the background g.setcolor(backgroundcolor); g.fillrect(0, 0, width, height); // Select the font and color for the message. g.setfont(font); g.setcolor(fontcolor); // Draw the message. g.drawstring(message, MESSAGE_LEFT, MESSAGE_TOP); // Draw the image. image.painticon(null, g, IMAGE_LEFT, IMAGE_TOP); } } 13