Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

My triangle won\'t appear on the screen. Can someone help me? package nervoussha

ID: 3758754 • Letter: M

Question

My triangle won't appear on the screen. Can someone help me?

package nervousshapes;

import java.awt.*;

public class NervousShapes {
// Constants
private static final int DELAY = 100;
    // Animation delay (milliseconds)
private static final int MAX_SIZE = 40;
    // Maximum width and height of a shape
private static final int MIN_SIZE = 10;
    // Minimum width and height of a shape
private static final int NUM_SHAPES = 90;
    // Number of shapes
private static final int WINDOW_SIZE = 400;
    // Width and height of drawable portion of frame

private static final int CHANGE_RANGE = 2;
// how far the new position can be from the previous position

private static DrawingPanel panel;
private static Graphics g;
    // Graphics context for frame
private static Shape shapes[] = new Shape[NUM_SHAPES];
    // Array of shapes

public static void main(String[] args) {
    createWindow();
    createShapes();
    animateShapes();
}

private static void createWindow() {
    // Create the drawing panel
   panel = new DrawingPanel(WINDOW_SIZE, WINDOW_SIZE);

    // Get the graphics context
    g = panel.getGraphics();
}


private static void createShapes ()

    {

        for (int i = 0; i < shapes.length; i++)

        {

            int red = generateRandomInt (0, 255);

            int green = generateRandomInt (0, 255);

            int blue = generateRandomInt (0, 255);

            double randomValue;

            Color color = new Color (red, green, blue);

            randomValue = Math.random ();

            if (randomValue < 0.5)

            {

                int diameter = generateRandomInt (MIN_SIZE, MAX_SIZE);

                int x = generateRandomInt (0, WINDOW_SIZE - diameter);

                int y = generateRandomInt (0, WINDOW_SIZE - diameter);

                shapes[i] = new Circle (x, y, color, diameter);

            }

            else if (randomValue > 0.5)

            {

                int width = generateRandomInt (MIN_SIZE, MAX_SIZE);

                int height = generateRandomInt (MIN_SIZE, MAX_SIZE);

                int x = generateRandomInt (0, WINDOW_SIZE - width);

                int y = generateRandomInt (0, WINDOW_SIZE - height);

                shapes[i] = new Rectangle (x, y, color, width, height);

            }

          

            else

            {

                int sideLength = generateRandomInt (MIN_SIZE, MAX_SIZE);

                int x = generateRandomInt (0, WINDOW_SIZE - sideLength);

                int y = generateRandomInt (0, WINDOW_SIZE - sideLength);

                shapes[i] = new Triangle (x, y, color, sideLength);

            }

        }

    }

    private static void animateShapes ()

    {

        while (true)

        {

            g.setColor (Color.white);

            g.fillRect (0, 0, WINDOW_SIZE - 1, WINDOW_SIZE - 1);

            for (int i = 0; i < shapes.length; i++)

            {

                int dx = generateRandomInt (-1, +1);

                int newX = shapes[i].getX () + dx;

                if (newX >= 0 && newX + shapes[i].getWidth () < WINDOW_SIZE)

                    shapes[i].move (dx, 0);

                int dy = generateRandomInt (-1, +1);

                int newY = shapes[i].getY () + dy;

                if (newY >= 0 && newY + shapes[i].getHeight () < WINDOW_SIZE)

                    shapes[i].move (0, dy);

                shapes[i].draw (g);

            }

            //panel.repaint();

            // Pause briefly

            try

            {

                Thread.sleep (DELAY);

            }

            catch (InterruptedException e)

            {}

        }

    }

    private static int generateRandomInt (int min, int max)

    {

        return (int) ((max - min + 1) * Math.random ()) + min;

    }

}


-----------------------------------------------------------------------

package nervousshapes;

import java.awt.*;

public class Triangle extends Shape {
// Instance variables
private int sideLength;

// Constructor
public Triangle(int x, int y, Color color,
                   int sideLength) {
    super(x, y, color);
    this.sideLength = sideLength;
}
// Instance methods
public void draw(Graphics g) {
    g.setColor(getColor());
    g.fillPolygon(getX(), getY(), sideLength, sideLength);
}

public int getHeight() {
    return sideLength;
}

public int getWidth() {
    return sideLength;
}
}

===========================================

package nervousshapes;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.event.*;

public class DrawingPanel implements ActionListener {
    public static final int DELAY = 50; // delay between repaints in millis

    private static final String DUMP_IMAGE_PROPERTY_NAME = "drawingpanel.save";
    private static String TARGET_IMAGE_FILE_NAME = null;
    private static final boolean PRETTY = true; // true to anti-alias
    private static boolean DUMP_IMAGE = true; // true to write DrawingPanel to file

    private int width, height;    // dimensions of window frame
    private JFrame frame;         // overall window frame
    private JPanel panel;         // overall drawing surface
    private BufferedImage image; // remembers drawing commands
    private Graphics2D g2;        // graphics context for painting
    private JLabel statusBar;     // status bar showing mouse position
    private long createTime;

    static {
        TARGET_IMAGE_FILE_NAME = System.getProperty(DUMP_IMAGE_PROPERTY_NAME);
        DUMP_IMAGE = (TARGET_IMAGE_FILE_NAME != null);
    }

    // construct a drawing panel of given width and height enclosed in a window
    public DrawingPanel(int width, int height) {
        this.width = width;
        this.height = height;
        this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        this.statusBar = new JLabel(" ");
        this.statusBar.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        this.panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
        this.panel.setBackground(Color.WHITE);
        this.panel.setPreferredSize(new Dimension(width, height));
        this.panel.add(new JLabel(new ImageIcon(image)));

        // listen to mouse movement
        MouseInputAdapter listener = new MouseInputAdapter() {
            public void mouseMoved(MouseEvent e) {
                DrawingPanel.this.statusBar.setText("(" + e.getX() + ", " + e.getY() + ")");
            }

            public void mouseExited(MouseEvent e) {
                DrawingPanel.this.statusBar.setText(" ");
            }
        };
        this.panel.addMouseListener(listener);
        this.panel.addMouseMotionListener(listener);

        this.g2 = (Graphics2D)image.getGraphics();
        this.g2.setColor(Color.BLACK);
        if (PRETTY) {
            this.g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            this.g2.setStroke(new BasicStroke(1.1f));
        }

        this.frame = new JFrame("Building Java Programs - Drawing Panel");
        this.frame.setResizable(false);
        this.frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                if (DUMP_IMAGE) {
                    DrawingPanel.this.save(TARGET_IMAGE_FILE_NAME);
                }
                System.exit(0);
            }
        });
        this.frame.getContentPane().add(panel);
        this.frame.getContentPane().add(statusBar, "South");
        this.frame.pack();
        this.frame.setVisible(true);
        if (DUMP_IMAGE) {
            createTime = System.currentTimeMillis();
            this.frame.toBack();
        } else {
            this.toFront();
        }

        // repaint timer so that the screen will update
        new Timer(DELAY, this).start();
    }

    // used for an internal timer that keeps repainting
    public void actionPerformed(ActionEvent e) {
        this.panel.repaint();
        if (DUMP_IMAGE && System.currentTimeMillis() > createTime + 4 * DELAY) {
            this.frame.setVisible(false);
            this.frame.dispose();
            this.save(TARGET_IMAGE_FILE_NAME);
            System.exit(0);
        }
    }

    // obtain the Graphics object to draw on the panel
    public Graphics2D getGraphics() {
        return this.g2;
    }

    // set the background color of the drawing panel
    public void setBackground(Color c) {
        this.panel.setBackground(c);
    }

    // show or hide the drawing panel on the screen
    public void setVisible(boolean visible) {
        this.frame.setVisible(visible);
    }

    // makes the program pause for the given amount of time,
    // allowing for animation
    public void sleep(int millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {}
    }

    // take the current contents of the panel and write them to a file
    public void save(String filename) {
        String extension = filename.substring(filename.lastIndexOf(".") + 1);

        // create second image so we get the background color
        BufferedImage image2 = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image2.getGraphics();
        g.setColor(panel.getBackground());
        g.fillRect(0, 0, this.width, this.height);
        g.drawImage(this.image, 0, 0, panel);

        // write file
        try {
            ImageIO.write(image2, extension, new java.io.File(filename));
        } catch (java.io.IOException e) {
            System.err.println("Unable to save image: " + e);
        }
    }

    // makes drawing panel become the frontmost window on the screen
    public void toFront() {
        this.frame.toFront();
    }
}


=============================================

// Represents a geometric shape that can be displayed in a
// graphics context
// This code is adapted from K. N. King: Java Programming: from the Beginning, 1st edition

package nervousshapes;

import java.awt.*;

public abstract class Shape {
// Instance variables
private int x;
private int y;
private Color color;

// Constructor
protected Shape(int x, int y, Color color) {
    this.x = x;
    this.y = y;
    this.color = color;
}
// Abstract methods
public abstract void draw(Graphics g);
public abstract int getHeight();
public abstract int getWidth();

// Other instance methods
public Color getColor() {
    return color;
}

public int getX() {
    return x;
}

public int getY() {
    return y;
}
public void move(int dx, int dy) {
    x += dx;
    y += dy;
}

public void setColor(Color color) {
    this.color = color;
}
}

Explanation / Answer

import java.awt.*;

public class NervousShapes

{

            // Constants

            private static final int DELAY = 10;

            // Animation delay (milliseconds)

            private static final int MAX_SIZE = 50;

            // Maximum width and height of a shape

            private static final int MIN_SIZE = 10;

                        private static final int NUM_SHAPES = 100;

                      private static final int WINDOW_SIZE = 500;

            private static DrawableFrame df;

            // Frame in which shapes are displayed

            private static Graphics g;

            private static Shape shapes[] = new Shape[NUM_SHAPES];

            private static void createWindow ()

            {

                        df = new DrawableFrame ("Nervous Shapes");

                        df.setVisible (true);

                        //df.show(); changed by ERB

                        df.setSize (WINDOW_SIZE, WINDOW_SIZE);

                        g = df.getGraphicsContext ();

            }

            private static void createShapes ()

            {

                        for (int i = 0; i < shapes.length; i++)

                        {

                                    // Select a random color

                                    int red = generateRandomInt (0, 255);

                                    int green = generateRandomInt (0, 255);

                                    int blue = generateRandomInt (0, 255);

                                    double randomValue;

                                    Color color = new Color (red, green, blue);

                                    randomValue = Math.random ();

                                    // Decide whether to create a circle or a rectangle

                                    if (randomValue < 0.5)

                                    {

                                                // Generate a circle with a random size and position

                                                int diameter = generateRandomInt (MIN_SIZE, MAX_SIZE);

                                                int x = generateRandomInt (0, WINDOW_SIZE - diameter);

                                                int y = generateRandomInt (0, WINDOW_SIZE - diameter);

                                                shapes[i] = new Circle (x, y, color, diameter);

                                    }

                                    else if (randomValue > 0.5)

                                    {

                                                // Generate a rectangle with a random size and

                                                // position

                                                int width = generateRandomInt (MIN_SIZE, MAX_SIZE);

                                                int height = generateRandomInt (MIN_SIZE, MAX_SIZE);

                                                int x = generateRandomInt (0, WINDOW_SIZE - width);

                                                int y = generateRandomInt (0, WINDOW_SIZE - height);

                                                shapes[i] = new Rectangle (x, y, color, width, height);

                                    }

                                    [color="#FF0000"]else

                                    {

                                                int sideLength = generateRandomInt (MIN_SIZE, MAX_SIZE);

                                                int x = generateRandomInt (0, WINDOW_SIZE - sideLength);

                                                int y = generateRandomInt (0, WINDOW_SIZE - sideLength);

                                                shapes[i] = new Triangle (x, y, color, sideLength);

                                    }[/color]

                                   

                        }

            }

            private static void animateShapes ()

            {

                        while (true)

                        {

                                    // Clear drawing area

                                    g.setColor (Color.white);

                                    g.fillRect (0, 0, WINDOW_SIZE - 1, WINDOW_SIZE - 1);

                                    for (int i = 0; i < shapes.length; i++)

                                    {

                                                // Change the x coordinate for shape i

                                                int dx = generateRandomInt (-1, +1);

                                                int newX = shapes[i].getX () + dx;

                                                if (newX >= 0 &&

                                                                        newX + shapes[i].getWidth () < WINDOW_SIZE)

                                                            shapes[i].move (dx, 0);

                                                // Change the y coordinate for shape i

                                                int dy = generateRandomInt (-1, +1);

                                                int newY = shapes[i].getY () + dy;

                                                if (newY >= 0 &&

                                                                        newY + shapes[i].getHeight () < WINDOW_SIZE)

                                                            shapes[i].move (0, dy);

                                                // Draw shape i at its new position

                                                shapes[i].draw (g);

                                    }

                                    // Call repaint to update the screen

                                    df.repaint ();

                        try

                                    {

                                                Thread.sleep (DELAY);

                                    }

                                    catch (InterruptedException e)

                                    {}

                        }

            }

            private static int generateRandomInt (int min, int max)

            {

                        return (int) ((max - min + 1) * Math.random ()) + min;

            }

            public static void main (String[] args)

            {

                        createWindow ();

                        createShapes ();

                        animateShapes ();

            }

}