QUICK MAX DUKE DOLLARS!!!

Project.java is a simple drawing program.
Modify the program to draw not only circles, but rectangles,
filled circles, filled rectanges and lines. Modify the program
so the user can change the color of a shape and clear the
drawing.
Use proper object orient techniques in making your modifications.
There is some code that is in the sample program that could
be improved. Make any modifications that you feel are necessary
to improve the code. The code simple shows you how to perform
the drawing operations.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
* This is a simply drawing program which lets the user draw basic shapes
* (lines, ovals and rectangles). This program currently only lets the
* user draw ovals, and the only color displayed is black.
* The drawing program uses rubberbanding so that the user can see the
* shape as they drag it. When the use clicks down on the mouse it
* sets the starting, or anchor, point for the drawing. When they release
* the button the shape is drawn. As the user holds down the button and
* drags the mouse, the shape is constantly displayed.
public class Project extends Panel
Panel controlPanel; // Contains for controls to determine shape and color
ScrollPane drawPane; // A scrollable drawing pane
Label shapeLabel; // A label for the shape drop down list
Label colorLabel; // a label for the color drop down list
Choice shapeChoice; // Drop down list (combbox) for selecting the shape
Choice colorChoice; // drop down lsit for selecting the color
Button clearButton; // For clearing the drawing canvas
Color currentColor = Color.black; // The current color used to draw shapes
DrawCanvas drawCanvas; // a Canva on which we draw the shapes
Vector shapes; // A vector to hold all of the shapes
protected String []shapeTypes = {"circle", "rectangle", "filled circle",
"filled rectangle", "line" };
protected String []colors = {"red", "blue", "green", "yellow", "orange",
"white", "black", "gray", "dark gray", "light gray",
"cyan", "magenta", "pink"};
Point anchorPoint; // The anchor point
Point endPoint; // The point where the mouse was released
Point stretchPoint; // The point where the user dragged the mouse to
Point lastPoint; // The previous drag point
boolean firstTime = true; // first time drawing this shape?
* Add GUI components
public Project()
// GridBagLayout is the most powerful and difficult to
// use Layout manager
// The layout manager determines were components are placed on
// the screen. There is no need to modify it in any way.
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gc = new GridBagConstraints();
// Create the control panel
setLayout(gbl);
controlPanel = new Panel();
setConstraints(controlPanel, gbl, gc, 0, 0,
GridBagConstraints.REMAINDER, 1, 0, 0,
GridBagConstraints.CENTER,
GridBagConstraints.NONE,
0, 0, 0, 0);
add(controlPanel, gc);
shapeLabel = new Label("Shape"); // The Label for the shape drop down list
controlPanel.add(shapeLabel);
shapeChoice = new Choice(); // The dropdown list
controlPanel.add(shapeChoice);
colorLabel = new Label("Color"); // The label or the color drop down list
controlPanel.add(colorLabel);
colorChoice = new Choice(); // The drop down list
controlPanel.add(colorChoice);
clearButton = new Button("Clear"); // the clear button
controlPanel.add(clearButton); // Doesn't do anything
// Event handelers
// Handle the event when the user selects a new shape
shapeChoice.addItemListener(new ShapeHandler());
// Event when user selects new color
colorChoice.addItemListener(new ColorHandler());
// Event when user click clear button
clearButton.addActionListener(new ClearHandler());
//Create the drawing area
drawPane = new ScrollPane();
setConstraints(drawPane, gbl, gc, 0, 1,
GridBagConstraints.REMAINDER, 1, 1, 1,
GridBagConstraints.CENTER,
GridBagConstraints.BOTH,
5, 0, 5, 0);
add(drawPane, gc);
drawPane.setSize(300,300);
drawCanvas = new DrawCanvas(400,400);
drawPane.add(drawCanvas);
initShapes(); // initialize the shape choice control
initColors(); // initialzie the color choice control
shapes = new Vector();
// Convenience method for GridBagLayout
private void setConstraints(
Component comp,
GridBagLayout gbl,
GridBagConstraints gc,
int gridx,
int gridy,
int gridwidth,
int gridheight,
int weightx,
int weighty,
int anchor,
int fill,
int top,
int left,
int bottom,
int right)
gc.gridx = gridx;
gc.gridy = gridy;
gc.gridwidth = gridwidth;
gc.gridheight = gridheight;
gc.weightx = weightx;
gc.weighty = weighty;
gc.anchor = anchor;
gc.fill = fill;
gc.insets = new Insets(top, left, bottom, right);
gbl.setConstraints(comp, gc);
// Initialize the shape control
private void initShapes()
for(int i = 0; i < shapeTypes.length; i++){
shapeChoice.add(shapeTypes);
// Initialzie the color control
private void initColors()
for(int i = 0; i < colors.length; i++){
colorChoice.add(colors);
* Handle the shape selection
* This doesn't currently do anything
public class ShapeHandler implements ItemListener
public void itemStateChanged(ItemEvent e)
// Use get index method to get the index of the chosen shape
// shapeType = shapeChoice.getSelectedItem();
* Handle the color seclection
* This doesn't do anything either
public class ColorHandler implements ItemListener
public void itemStateChanged(ItemEvent e)
String color = colorChoice.getSelectedItem();
System.out.println("Selected color " + color);
// Handle the clear button
// This doesn't do anything
public class ClearHandler implements ActionListener
public void actionPerformed(ActionEvent e)
* A canvas to draw on
public class DrawCanvas extends Component
int width; // The Width of the Canvas
int height; // The Height of the Canvas
/** Create an area to draw on
*@param width - the width of the drawing area
*@param height - the height of the drawing area
public DrawCanvas(int width, int height)
// Handle mouse press and release events
addMouseListener(new MouseHandler());
// handle mouse drag events
addMouseMotionListener(new MouseDragHandler());
this.width = width;
this.height = height;
* Draw all of the shapes
* Not very efficient
public void paint(Graphics g)
for (Enumeration e = shapes.elements() ; e.hasMoreElements() ;)
Circle c = (Circle )e.nextElement();
System.out.println("drawing Circle " + c.toString());
c.draw(g);
* Let everyone know what the preferred size of the drawing
* canvas is
public Dimension getPreferredSize()
return new Dimension(width, height);
* Used with rubberbanding. The way to erase a shape is
* to draw it again in XOR mode.
private void eraseLast(Graphics g)
int x, y;
int width, height;
if (anchorPoint == null || lastPoint == null)
return;
// The draw methods assume that the width and height are
// not negative so we do the following caculations to
// insure that they are not
if (anchorPoint.x < lastPoint.x)
x = anchorPoint.x;
else
x = lastPoint.x;
if (anchorPoint.y < lastPoint.y)
y = anchorPoint.y;
else
y = lastPoint.y;
width = Math.abs(lastPoint.x - anchorPoint.x);
height = Math.abs(lastPoint.y - anchorPoint.y);
// Draw the circle (or oval) at the rectagle bounded by
// the rectange with the upper left hand corner of x,y
// and with the specified width and height
g.drawOval(x, y, width, height);
// To draw a rectable
//g.drawRect(x, y, width, height);
// To draw a Filled Oval
//g.fillOval(x, y, width, height);
// To draw a Filled Rect
//g.fillRect(x, y, width, height);
// To draw a line
//g.drawLine(anchorPoint.x, anchorPoint.y, lastPoint.x, lastPoint.y);
* Do the rubber band drawing
private void drawRubber(Graphics g)
int x, y;
int width, height;
if (anchorPoint.x < stretchPoint.x)
x = anchorPoint.x;
else
x = stretchPoint.x;
if (anchorPoint.y < stretchPoint.y)
y = anchorPoint.y;
else
y = stretchPoint.y;
width = Math.abs(stretchPoint.x - anchorPoint.x);
height = Math.abs(stretchPoint.y - anchorPoint.y);
g.drawOval(x, y, width, height);
* Handle the start and end of rubberbanding. At the end
* draw the final shape
public class MouseHandler extends MouseAdapter
// Get the starting point
public void mousePressed(MouseEvent e)
anchorPoint = e.getPoint(); // Point where mouse was clickec
firstTime = true; // The first point
// Get the end point
public void mouseReleased(MouseEvent e)
endPoint = e.getPoint(); // Point where mouse was released
Graphics g = getGraphics(); // Get the object to draw on
g.setXORMode(getBackground()); // Set XOR mode
eraseLast(g); // Erase the previous shape
// Add the shape to our vector
//Obviously you will need to do something different here
shapes.addElement( new Circle(anchorPoint, endPoint, currentColor));
repaint(); // Repaint the entire drawing
g.dispose(); // Need to dispose of Graphics objects
* Handle the rubber banding
public class MouseDragHandler extends MouseMotionAdapter
// Every time the mouse is moved while the mouse button is pressed
public void mouseDragged(MouseEvent e)
Graphics g = getGraphics();
g.setXORMode(getBackground());
stretchPoint = e.getPoint(); // Get the point we just dragged to
if (firstTime == true)
firstTime = false; // nothing to erase the first time
else
eraseLast(g); // Erase the last drawing
drawRubber(g); // Draw the new one
g.dispose(); // Anytime we do a getGraphics we must dispose of it
lastPoint = stretchPoint; // Set the lastPoint to lastest last point
* In real program this should extend Shape or implement a Shape
* interface and it should be in it's own file
* Note that even though this is called Circle, it is really an oval
public class Circle
int x, y; // X and Y cooridinates of bounding rectangle (upper left)
int width, height; // width and height of bounding rectangle
Point p2; // opposite corner of bounding retangle
Color color; // color of circle
public Circle(Point p1, Point p2, Color color)
// The width and height cannot be negative.
// x and y must always be the upper left corner
if ( p1.x < p2.x)
x = p1.x;
else
x = p2.x;
if (p1.y < p2.y)
y = p1.y;
else
y = p2.y;
width = Math.abs( p2.x - p1.x);
height = Math.abs(p2.y - p1.y);
this.color = color;
* This method is called automatically by repaint and whenever the
* window needs to be redrawn
public void draw(Graphics g)
Color c = g.getColor(); // Save the current color
g.setColor(color); // Set the color to draw the circle
g.drawOval(x, y, width, height); // draw the circle
g.setColor(c); // set the color back to what is was before
* a toString method is a convienent way of
* displaying the attributes of a class
public String toString()
return "Circle " + color + width + height;
* Main method creates a Frame and adds in our drawing control
public static void main(String []args)
// Create the main window
Frame frame = new Frame();
// add a listener to close the window properly
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0); // simply exit
// Create our control
Project panel = new Project();
// add it to our window
frame.add(panel, BorderLayout.CENTER);
// size our window to 640 by 480 pixels
frame.setSize(640, 480);
// display our window
frame.setVisible(true);
}

Sure, I'll do it, no problem... Anything to help a fellow hard working computer science student... I'm just curious what college you attend. Could you tell me? I promise I'll get you the code then.

Similar Messages

  • Duke Dollars give away

    Hi
    I have some duke dollars which i have assigned to a post, but no one seems to answer me the question properly, So i am asking people to quickly push some valid answers for this and claim their worthy duke dollars.
    To claim the duke dollars kindly go to this thread and answer it
    9 duke dollars are available
    http://forums.java.sun.com/thread.jsp?forum=45&thread=133596
    Thanks
    Swaraj

    The duke dollars are over.
    Thanks
    Swaraj

  • I'm trying to make i(to the power of n) over n.quickanswer=MANY duke dollar

    I will pay many duke dollars for a quick answer to this.
    i(to the power of)n
    the full equation is r=---
    n
    heres what i did:
    class Project
         public static void main(String[] arguments) {
              int P = 0;
              int r = 0;
              int n = 0;
              int t = 0;
              int i = 0     
              int interest = i public static double exp(n) / n;
              system.out.print("The Interest rate is" + interest);
              int rate = 1 + r public static double exp(1/n) h;//the effective rate
              system.out.println("The effective rate is" + rate);
         int A = P (1 + i public static double exp(n) /n) public static double exp(n*t);
    The program isn't finished i have to get this far without errors

    one last thing. could you just go over this briefly and quickly?
    class Project { 
         public static void main(String[] arguments) {
              int P = 0;
              int r = 0;
              int n = 0;
              int t = 0;
              int i = 0;     
              //these values are put in by you, the user.
              int interest = Math.pow(i, n) / n;
    system.out.print("The Interest rate is" + interest);
              int rate = Math.pow((1 + r), 1/n) ;//the effective rate
    system.out.println("The effective rate is" + rate);
              int A = P * Math.pow( (1 + Math.pow(i, n) / n), n * t); system.out.print("The total holdings (A) is" + A);
              int e = Math.pow(1 + (1 / n), n);     system.out.print("The return (e) is" + e);
              int time = P Math.pow(1 + r, t);
    system.out.print("The time needed to double?");
    system.out.print("The time needed for this principal is" + time);

  • How do you add Duke Dollars to a post???

    How do you get the little Duke Dollars thingy to show up next to your post? There are no buttons to do so on the page where I'm ttyping this, nor on the preview page. Nor does it say anything about it in the Duke Dollars FAQ.

    Oh never mind! I saw the option to add Dukes appear after the message was posted.
    IMHO you should be able to add Dukes either on the form or the preview page.

  • Using WAIT to repeatedly check a file !!Duke dollars!!

    I have created this method, it is supposed to read a text file when a button is pressed after i have allocated an amount of time to check the text file. the text file must be checked every 2mins or so to see if there have been any changes!
    i have some code here but 'wait(10000)' doesnt seem to have any effect!
    can anybody help
    theres 15 duke dollars in it for the best solution
    cheers everyone
    private void polling()
    try {
    wait(10000);
    } catch (Exception e){
    try {
    Stack male = new Stack();
              Stack female = new Stack();
              File esbian = new File("02May2002_Test_Facts.txt");
              FileReader ond = new FileReader(esbian);
              BufferedReader hecker = new BufferedReader(ond);
    int ef;
    String incident = "INCIDENT" ;
              while (true)
                   String lum = new String();
                   String umber = "";
                   String olyfeck = hecker.readLine();
                   if (olyfeck == null)
                        break;
                   StringTokenizer tarman = new StringTokenizer(olyfeck);
                   while (tarman.hasMoreTokens())
    umber = tarman.nextToken();
                        for( ef=0; ef < 1; ef++)
    umber = umber.replace('\u0028' , '\u0020');
    umber = umber.replace('\u0029' , '\u0020');
                        umber = umber.trim().toUpperCase();
    if (umber.equals("INCIDENT" ) || umber.equals("EVENT") ||umber.equals("ALARM") || umber.equals("FAULTRECORD") || umber.equals("INTERPRETEDFAULTRECORD"))
    lum = umber;
                             agentout.append("subscription succeeded: " + umber + "\r\n");
              hecker.close();
    catch(IOException efe)
         System.err.println("ERROR: " + efe) ;
    } // end of method polling

    I have created this method, it is supposed to read a text file when a button is pressed after i have allocated an amount of time to check the text file. the text file must be checked every 2mins or so to see if there have been any changes!
    i have some code here but 'wait(10000)' doesnt seem to have any effect!
    can anybody help
    theres 15 duke dollars in it for the best solution
    cheers everyone
    private void polling()
    try {
    wait(10000);
    } catch (Exception e){
    try {
    Stack male = new Stack();
              Stack female = new Stack();
              File esbian = new File("02May2002_Test_Facts.txt");
              FileReader ond = new FileReader(esbian);
              BufferedReader hecker = new BufferedReader(ond);
    int ef;
    String incident = "INCIDENT" ;
              while (true)
                   String lum = new String();
                   String umber = "";
                   String olyfeck = hecker.readLine();
                   if (olyfeck == null)
                        break;
                   StringTokenizer tarman = new StringTokenizer(olyfeck);
                   while (tarman.hasMoreTokens())
    umber = tarman.nextToken();
                        for( ef=0; ef < 1; ef++)
    umber = umber.replace('\u0028' , '\u0020');
    umber = umber.replace('\u0029' , '\u0020');
                        umber = umber.trim().toUpperCase();
    if (umber.equals("INCIDENT" ) || umber.equals("EVENT") ||umber.equals("ALARM") || umber.equals("FAULTRECORD") || umber.equals("INTERPRETEDFAULTRECORD"))
    lum = umber;
                             agentout.append("subscription succeeded: " + umber + "\r\n");
              hecker.close();
    catch(IOException efe)
         System.err.println("ERROR: " + efe) ;
    } // end of method polling

  • Assigning duke dollars

    How do I award Duke dollars to the best respondent to my question?

    After you post a question, there will be a hyperlink like "assign duke dollar" in the page of your post. Follow it to assign the duke dollar to your question. To reward the duke dollar to the response, you have to log in first, open your post, then you can see a icon in front of every repsponse, you can click the one you want to reward.

  • I wanna assign you ALL my Duke Dollars....

    ...for a new question i have BUT b4 I can do that I need to retrive back the duke dollars from my earlier messages that haven't been answered and have my dollars gathering dust...how on earth do i do that?

    Silkm I have no issues with assigning you all my dukes from all those earlier questions...just go there, type anything and I will assign them to you if u can solve my query...
    It's gotta do with setting the classpath...and yes, i have already been thru google and forums here...
    This is what i do:
    - Start>Control Panel>System>Advanced>Environment Variables
    - Click on Path in the System Variables section
    - Click Edit and add C:\Program Files\Java\j2re1.4.1_01\bin AFTER %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;c:\Program Files\Common Files\Adaptec Shared\System;
    - Next I go to DOS and get my C prompt to C:\Program Files\Java\j2re1.4.1_01\bin
    - I type javac helloworld.java and ENTER
    - I get "javac is not recognised as an internal or external command, operable program or batch file"
    So then I go back to Start>Control Panel>System>Advanced>Environment Variables
    - This time I click on New in the "User Variables for Gaurav" section(that's me) - after all i am logged in as Gaurav on my XP machine!
    - I type Path in Variable Name and C:\Program Files\Java\j2re1.4.1_01\bin in Variable Value
    - Save
    - goto DOS
    - type helloworld.java and get "javac is not recognised as an internal or external command, operable program or batch file"
    BTW i have installed j2re-1_4_1_01-windows-i586 on a XP machine
    HELP!

  • How do you award duke dollars

    How do you award duke dollars

    At the top of your post, ther will be an option to "Assign" duke dollars. Once you assign them to your post, you will see an option to "Award" duke dollars in the header of the replies to the post.
    Why don't you assign a few to this post to witness that! :-)
    Kamran

  • Next/previous links?  Duke dollars...

    I am offering Duke Dollars for help in creating next/previous links here:
    http://forum.java.sun.com/thread.jsp?forum=45&thread=183010
    I was told that I should ask here as there may be more help here...

    Actually I think that respondant was suggesting that you search the JDBC forum - they had already posted some information in here.

  • HI what are duke dollars?

    Hi everyone, just joined the JDC - I am a complete newbie here, what are DUKE DOLLARS? Can you educate me on some things you guys do on the forums? Thanks! :)
    cp_l0g1ck

    That's in the FAQ which you can see here: http://forum.java.sun.com/faq.jsp

  • Duke Dollars, What are they and why are they in this forum?

    Hi,
    Can somebody please tell me what duke dollars are and why they are in this forum? some topics have duke dollars, but don't know what that means.
    Thanks in advance
    Arjen

    hahahahha... the moment i posted this topic, i received the link to assigning dollars to a topic as well as a link to what duke dollars are. :) lol

  • Cant assign duke dollars --not working why ?

    cannot see the assign duke dollar button why ?

    I'd tell you if there were some Dukes on offer.

  • Duke Dollars Not Working

    I tried to assign Duke Dollars to my last post. It says that I have 50 dollars to assign. Whne I try to assign them I get a 500 Server error. i kept trying and it eventually displayed a stack trace stating the user has insufficient dollars. What Gives?

    I'd tell you if there were some Dukes on offer.

  • Who has the most duke dollars?

    Is there a place in the JDC where you find find a list of who had the most duke dollars? I think they had this a long time ago, but I'm not sure what happend to it.
    Thanks,
    Strider

    http://developer.java.sun.com/developer/community/dd.jshtml#winners
    (Do I get any duke dollars for this?)

  • Where's my monthly duke dollars?

    according to the faq "Duke dollars: JDC members acquire Duke Dollars upon registration, then again on a monthly basis. "
    I dont know enough to earn dukes (yet)... so i count on getting this... otherwise i will have to continue being cheap! I dont like being miserly with my dukes : (
    PS While i have your attention, Christmas is coming - so can i make a request for "lots" of dukes?? ; )

    they are hiding under the Chrismas Tree.

Maybe you are looking for

  • "Name Dictionary" not found in "document catalog" of PDF

    Hi All, I am working with a PDF parser and while parsing a PDF file I found that while reading document catalog of PDF, the "Name Dictionary" which I got is not present in PDF file but When I updated to Adobe Reader X it seems to be working fine. So,

  • Need Help With Processing A Delay

    OK I'm working on a Flash intro for a site. After the Flash movie plays I want it to wait three seconds and then send them to the index page. Currently I'm using the action script: stop(); getURL("http://mywebsite.com/index.php", "_top", "GET"); I've

  • What is the URL that Adobe Acrobat needs to contact for Activation after you enter the serial number

    What is the URL that Adobe Acrobat needs to contact for Activation after you enter the serial number? We need to allow internet access to our users for it.

  • Keeping an application session open

    Internet Sales (ISA) integrated in the portal. The problem we're currently facing is the following: We integrated the ISA application into the portal, we are using the SSO and this works just fine. We're trying to maintain or basket contenence even w

  • h1 The Use Of Header Tags

    I'm becoming more aware of the importance of using header tags to help the visually impaired navigate your site.  Obviously the main header should be wrapped in an <h1> tag, however after that does it flow from <h1> all the way to <h6>, and what if y