SlideShare a Scribd company logo
ANIMATE YOUR CODE: JAVA ASSIGNMENT
SAMPLES!
Programming in Java: Building
Software with Objects, Graphics, and
Animation
Introduction
 Objective: Learn how to create and animate
graphical objects in Java.
 Topics Covered:
 Object-Oriented Programming (OOP) in Java
 Java’s built-in graphics and containers
 Creating and animating shapes
 Key Features:
 Simple, secure, and robust
 Multithreading capabilities
 Rich API for building diverse applications
Understanding the Classes
 SimpleDraw:Manages the window and rendering
 Contains the main method
 BouncingBox:Represents a box that moves and
bounces within the window
 DrawGraphics:Manages drawing and animating
graphics on the screen
In the last assignment you learned how to create your own simple objects. One of the
advantages of building software using objects is that it makes it relatively easy to use
software components that other people have built. In this assignment, you will use
the Java's built-in graphics and containers, combined with a simple framework that
we provide. Add three different shapes to the initial window we provide.
Requirements:
Add three instances of the BouncingBox class to your window, moving in different
directions. Use an ArrayList to hold them.
Setup:
1.(Optional) Create a new project in Eclipse, with whatever name you want.
2.Create three classes: SimpleDraw, BouncingBox, and DrawGraphics. Copy and
paste the code for these classes from below.
3.Run the example program. If Eclipse gives you trouble, open SimpleDraw and run
that, as it contains the main method for the program. You should see a window that
looks like the following:
Part 1: Drawing Graphics
Open the DrawGraphics class. The draw method is what draws the contents of the
window. Currently, there is a line and a square with a border around it. Feel free to
remove these, if you want. Add at least three different shapes to the window. Read
the API documentation for the java.awt.Graphics class to find what methods are
provided. You can draw rectangles, arcs, lines, text, ovals, polygons, and, if you
want to do some extra work, images. Be creative!
Note: You should only modify the DrawGraphics class for this step. The other
classes contain a bunch of code required to create a window in Java that you do
not need to change or understand.
Part 2 : Containers & Animations
The DrawGraphics class supports animation. The draw method gets called 20
times a second, in order to draw each individual frame. The BouncingBox class
also includes animation support. To get the box to move, call setMovementVector
method from the DrawGraphics constructor, providing an x and y offset. For
example, the value (1, 0) moves the box to the right slowly, while (0, -2) will move
it up faster. You only need to call this method once to keep it moving in that
direction. In other words, don't call setMovementVector from the draw method,
call it from the constructor.
Add at least three boxes to your window, moving in different directions. To do
this, put three BouncingBox instances in an ArrayList, as part of the
DrawGraphics constructor. Then, call the draw method on each of the boxes from
DrawGraphics.draw, using a loop.
Optional: If you want to experiment, create your own animated object. Copy
BouncingBox as a starting point, then edit the code in its draw method. You
could create something with more complicated movement, and/or something
that looks better than what I created in five minutes.
Submission Instructions:
Submit your DrawGraphics.java file via Stellar.
SampleDraw.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** Displays a window and delegates drawing to DrawGraphics. */
public class SimpleDraw extends JPanel implements Runnable {
private static final long serialVersionUID =-7469734580960165754L;
private boolean animate = true;
private final int FRAME_DELAY = 50; // 50 ms = 20 FPS
public static final int WIDTH = 300; public static final int HEIGHT = 300; private
DrawGraphics draw;
public SimpleDraw(DrawGraphics drawer){
this.draw = drawer;
}
/** Paint callback from Swing. Draw graphics using g. */
public void paintComponent(Graphics g){
super.paintComponent(g);
// Enable anti-aliasing for better looking graphics
Graphics2D g2 =(Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
draw.draw(g2);
}
/** Enables periodic repaint calls. */
public synchronized void start() {
animate = true;
}
/** Pauses animation. */
public synchronized void stop() {
animate = false;
}
private synchronized boolean animationEnabled() {
return animate;
}
public void run() {
while (true){
if (animationEnabled()) {
repaint();
}
try {
Thread.sleep(FRAME_DELAY);
} catch (InterruptedException e){
throw new RuntimeException(e);
}}
}
public static void main(String args[]) { final SimpleDraw content = new
SimpleDraw(new DrawGraphics());
JFrame frame = new JFrame("Graphics!");
Color bgColor = Color.white;
frame.setBackground(bgColor);
content.setBackground(bgColor);
// content.setSize(WIDTH, HEIGHT); // content.setMinimumSize(new
Dimension(WIDTH, HEIGHT));
content.setPreferredSize(new Dimension(WIDTH, HEIGHT));
// frame.setSize(WIDTH, HEIGHT);
frame.setContentPane(content);
frame.setResizable(false);
frame.pack();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){ System.exit(0); } public void
windowDeiconified(WindowEvent e){ content.start(); } public void
windowIconified(WindowEvent e){ content.stop(); }
});
new Thread(content).start();
frame.setVisible(true);
}
}
DrawGraphics.java
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class BouncingBox {
int x;
int y;
Color color;
int xDirection = 0;
int yDirection = 0;
final int SIZE = 20;
/**
*
Initialize a new box with its center located at (startX, startY), filled
*
with startColor.
*/
public BouncingBox(int startX, int startY, Color startColor){
x = startX;
y = startY;
color = startColor;
}
/** Draws the box at its current position on to surface. */
public void draw(Graphics surface){
// Draw the object
surface.setColor(color);
surface.fillRect(x - SIZE/2, y - SIZE/2, SIZE, SIZE);
surface.setColor(Color.BLACK);
((Graphics2D) surface).setStroke(new BasicStroke(3.0f));
surface.drawRect(x - SIZE/2, y - SIZE/2, SIZE, SIZE);
// If we have hit the edge and are moving in the wrong direction, reverse direction
// We check the direction because if a box is placed near the wall, we would get
"stuck" // rather than moving in the right direction
if ((x - SIZE/2 <= 0 && xDirection < 0) ||
(x + SIZE/2 >= SimpleDraw.WIDTH && xDirection > 0)) {
xDirection =-xDirection;
}
if ((y - SIZE/2 <= 0 && yDirection < 0) ||
(y + SIZE/2 >= SimpleDraw.HEIGHT && yDirection > 0)) {
yDirection =-yDirection;
}
}
public void setMovementVector(int xIncrement, int yIncrement){ xDirection =
xIncrement; yDirection = yIncrement;
}
}
// Move the center of the object each time we draw it
x += xDirection;
y += yDirection;
DrawGraphics.java
import java.awt.Color;
import java.awt.Graphics;
public class DrawGraphics {
BouncingBox box;
/** Initializes this class for drawing. */
public DrawGraphics() {
box = new BouncingBox(200, 50, Color.RED);
}
/** Draw the contents of the window on surface. Called 20 times per second. */
public void draw(Graphics surface){
surface.drawLine(50, 50, 250, 250);
box.draw(surface);
}
}
BouncingBox.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** Displays a window and delegates drawing to DrawGraphics. */
public class SimpleDraw extends JPanel implements Runnable {
private static final long serialVersionUID = -7469734580960165754L;
private boolean animate = true;
private final int FRAME_DELAY = 50; // 50 ms = 20 FPS
public static final int WIDTH = 300;
public static final int HEIGHT = 300;
private DrawGraphics draw;
public SimpleDraw(DrawGraphics drawer) {
this.draw = drawer;
}
/** Paint callback from Swing. Draw graphics using g. */
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Enable anti-aliasing for better looking graphics
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
draw.draw(g2);
}
/** Enables periodic repaint calls. */
public synchronized void start() {
animate = true;
}
/** Pauses animation. */
public synchronized void stop() {
animate = false;
}
private synchronized boolean animationEnabled() {
return animate;
}
public void run() {
while (true) {
if (animationEnabled()) {
repaint();
}
try {
Thread.sleep(FRAME_DELAY);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String args[]) {
final SimpleDraw content = new SimpleDraw(new DrawGraphics());
JFrame frame = new JFrame("Graphics!");
Color bgColor = Color.white;
frame.setBackground(bgColor);
content.setBackground(bgColor);
// content.setSize(WIDTH, HEIGHT);
// content.setMinimumSize(new Dimension(WIDTH, HEIGHT));
content.setPreferredSize(new Dimension(WIDTH, HEIGHT));
// frame.setSize(WIDTH, HEIGHT);
frame.setContentPane(content);
frame.setResizable(false);
frame.pack();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
public void windowDeiconified(WindowEvent e) { content.start(); }
public void windowIconified(WindowEvent e) { content.stop(); }
});
new Thread(content).start();
frame.setVisible(true);
}
}
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class BouncingBox {
int x;
int y;
Color color;
int xDirection = 0;
int yDirection = 0;
final int SIZE = 20;
/**
Initialize a new box with its center located at (startX, startY), filled
* with startColor.
*/
public BouncingBox(int startX, int startY, Color startColor) {
x = startX;
y = startY;
color = startColor;
}
/** Draws the box at its current position on to surface. */
public void draw(Graphics surface) {
// Draw the object
surface.setColor(color);
surface.fillRect(x - SIZE/2, y - SIZE/2, SIZE, SIZE);
surface.setColor(Color.BLACK);
((Graphics2D) surface).setStroke(new BasicStroke(3.0f));
surface.drawRect(x - SIZE/2, y - SIZE/2, SIZE, SIZE);
// Move the center of the object each time we draw it
x += xDirection;
y += yDirection;
// If we have hit the edge and are moving in the wrong direction, reverse direction
// We check the direction because if a box is placed near the wall, we would get
"stuck"
// rather than moving in the right direction
if ((x - SIZE/2 <= 0 && xDirection < 0) ||
(x + SIZE/2 >= SimpleDraw.WIDTH && xDirection > 0)) {
xDirection = -xDirection;
}
if ((y - SIZE/2 <= 0 && yDirection < 0) ||
(y + SIZE/2 >= SimpleDraw.HEIGHT && yDirection > 0)) {
yDirection = -yDirection;
}
}
public void setMovementVector(int xIncrement, int yIncrement) {
xDirection = xIncrement;
yDirection = yIncrement;
}
}
import java.awt.Color;
import java.awt.Graphics;
public class DrawGraphics {
BouncingBox box;
/** Initializes this class for drawing. */
public DrawGraphics() {
box = new BouncingBox(200, 50, Color.RED);
}
/** Draw the contents of the window on surface. Called 20 times per second. */
public void draw(Graphics surface) {
surface.drawLine(50, 50, 250, 250);
box.draw(surface);
}
}
Summary:
Reviewed Java basics, OOP principles, graphics, containers, and animation
Provided sample code and project ideas
Next Steps:
Experiment with code examples
Start building your own Java applications
Explore advanced Java topics and libraries
Contact Information:
For more help and custom programming assignments, visit
programminghomeworkhelp.com

More Related Content

Similar to Java Assignment Sample: Building Software with Objects, Graphics, Containers, and Animation (20)

Lec 7 28_aug [compatibility mode]
Lec 7 28_aug [compatibility mode]Lec 7 28_aug [compatibility mode]
Lec 7 28_aug [compatibility mode]
Palak Sanghani
 
Java swing
Java swingJava swing
Java swing
Arati Gadgil
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
Jussi Pohjolainen
 
Client Side Programming with Applet
Client Side Programming with AppletClient Side Programming with Applet
Client Side Programming with Applet
backdoor
 
Java Foundation Classes - Building Portable GUIs
Java Foundation Classes - Building Portable GUIsJava Foundation Classes - Building Portable GUIs
Java Foundation Classes - Building Portable GUIs
Arun Seetharaman
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة التاسعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة التاسعةشرح مقرر البرمجة 2   لغة جافا - الوحدة التاسعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة التاسعة
جامعة القدس المفتوحة
 
Lec 10 10_sept [compatibility mode]
Lec 10 10_sept [compatibility mode]Lec 10 10_sept [compatibility mode]
Lec 10 10_sept [compatibility mode]
Palak Sanghani
 
Creating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdfCreating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdf
ShaiAlmog1
 
ch03g-graphics.ppt
ch03g-graphics.pptch03g-graphics.ppt
ch03g-graphics.ppt
Mahyuddin8
 
I am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdfI am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdf
seamusschwaabl99557
 
Lec 11 12_sept [compatibility mode]
Lec 11 12_sept [compatibility mode]Lec 11 12_sept [compatibility mode]
Lec 11 12_sept [compatibility mode]
Palak Sanghani
 
JavaFX Overview
JavaFX OverviewJavaFX Overview
JavaFX Overview
José Maria Silveira Neto
 
Online birth certificate system and computer engineering
Online birth certificate system and computer engineeringOnline birth certificate system and computer engineering
Online birth certificate system and computer engineering
sayedshaad02
 
An Introduction to Computer Science with Java .docx
An Introduction to  Computer Science with Java .docxAn Introduction to  Computer Science with Java .docx
An Introduction to Computer Science with Java .docx
daniahendric
 
Unit – I-AWT-updated.pptx
Unit – I-AWT-updated.pptxUnit – I-AWT-updated.pptx
Unit – I-AWT-updated.pptx
ssuser10ef65
 
Hacking JavaFX with Groovy, Clojure, Scala, and Visage: Stephen Chin
Hacking JavaFX with Groovy, Clojure, Scala, and Visage: Stephen ChinHacking JavaFX with Groovy, Clojure, Scala, and Visage: Stephen Chin
Hacking JavaFX with Groovy, Clojure, Scala, and Visage: Stephen Chin
jaxconf
 
Java Graphics
Java GraphicsJava Graphics
Java Graphics
Shraddha
 
Program imageviewer
Program imageviewerProgram imageviewer
Program imageviewer
Fajar Baskoro
 
unit3.3.pptx
unit3.3.pptxunit3.3.pptx
unit3.3.pptx
VeenaNaik23
 
Swing basics
Swing basicsSwing basics
Swing basics
Medi-Caps University
 
Lec 7 28_aug [compatibility mode]
Lec 7 28_aug [compatibility mode]Lec 7 28_aug [compatibility mode]
Lec 7 28_aug [compatibility mode]
Palak Sanghani
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
Jussi Pohjolainen
 
Client Side Programming with Applet
Client Side Programming with AppletClient Side Programming with Applet
Client Side Programming with Applet
backdoor
 
Java Foundation Classes - Building Portable GUIs
Java Foundation Classes - Building Portable GUIsJava Foundation Classes - Building Portable GUIs
Java Foundation Classes - Building Portable GUIs
Arun Seetharaman
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة التاسعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة التاسعةشرح مقرر البرمجة 2   لغة جافا - الوحدة التاسعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة التاسعة
جامعة القدس المفتوحة
 
Lec 10 10_sept [compatibility mode]
Lec 10 10_sept [compatibility mode]Lec 10 10_sept [compatibility mode]
Lec 10 10_sept [compatibility mode]
Palak Sanghani
 
Creating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdfCreating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdf
ShaiAlmog1
 
ch03g-graphics.ppt
ch03g-graphics.pptch03g-graphics.ppt
ch03g-graphics.ppt
Mahyuddin8
 
I am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdfI am sorry but my major does not cover programming in depth (ICT) an.pdf
I am sorry but my major does not cover programming in depth (ICT) an.pdf
seamusschwaabl99557
 
Lec 11 12_sept [compatibility mode]
Lec 11 12_sept [compatibility mode]Lec 11 12_sept [compatibility mode]
Lec 11 12_sept [compatibility mode]
Palak Sanghani
 
Online birth certificate system and computer engineering
Online birth certificate system and computer engineeringOnline birth certificate system and computer engineering
Online birth certificate system and computer engineering
sayedshaad02
 
An Introduction to Computer Science with Java .docx
An Introduction to  Computer Science with Java .docxAn Introduction to  Computer Science with Java .docx
An Introduction to Computer Science with Java .docx
daniahendric
 
Unit – I-AWT-updated.pptx
Unit – I-AWT-updated.pptxUnit – I-AWT-updated.pptx
Unit – I-AWT-updated.pptx
ssuser10ef65
 
Hacking JavaFX with Groovy, Clojure, Scala, and Visage: Stephen Chin
Hacking JavaFX with Groovy, Clojure, Scala, and Visage: Stephen ChinHacking JavaFX with Groovy, Clojure, Scala, and Visage: Stephen Chin
Hacking JavaFX with Groovy, Clojure, Scala, and Visage: Stephen Chin
jaxconf
 
Java Graphics
Java GraphicsJava Graphics
Java Graphics
Shraddha
 

More from Programming Homework Help (20)

Data Structures and Algorithm: Sample Problems with Solution
Data Structures and Algorithm: Sample Problems with SolutionData Structures and Algorithm: Sample Problems with Solution
Data Structures and Algorithm: Sample Problems with Solution
Programming Homework Help
 
Seasonal Decomposition of Time Series Data
Seasonal Decomposition of Time Series DataSeasonal Decomposition of Time Series Data
Seasonal Decomposition of Time Series Data
Programming Homework Help
 
Solving Haskell Assignment: Engaging Challenges and Solutions for University ...
Solving Haskell Assignment: Engaging Challenges and Solutions for University ...Solving Haskell Assignment: Engaging Challenges and Solutions for University ...
Solving Haskell Assignment: Engaging Challenges and Solutions for University ...
Programming Homework Help
 
Exploring Control Flow: Harnessing While Loops in Python
Exploring Control Flow: Harnessing While Loops in PythonExploring Control Flow: Harnessing While Loops in Python
Exploring Control Flow: Harnessing While Loops in Python
Programming Homework Help
 
C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
Programming Homework Help
 
Python Question - Python Assignment Help
Python Question - Python Assignment HelpPython Question - Python Assignment Help
Python Question - Python Assignment Help
Programming Homework Help
 
Best Algorithms Assignment Help
Best Algorithms Assignment Help Best Algorithms Assignment Help
Best Algorithms Assignment Help
Programming Homework Help
 
Design and Analysis of Algorithms Assignment Help
Design and Analysis of Algorithms Assignment HelpDesign and Analysis of Algorithms Assignment Help
Design and Analysis of Algorithms Assignment Help
Programming Homework Help
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
Programming Homework Help
 
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptxprogramminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
Programming Homework Help
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
Programming Homework Help
 
Algorithms Design Assignment Help
Algorithms Design Assignment HelpAlgorithms Design Assignment Help
Algorithms Design Assignment Help
Programming Homework Help
 
Algorithms Design Homework Help
Algorithms Design Homework HelpAlgorithms Design Homework Help
Algorithms Design Homework Help
Programming Homework Help
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
Programming Homework Help
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
Programming Homework Help
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
Programming Homework Help
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
Programming Homework Help
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
Programming Homework Help
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
Programming Homework Help
 
Computer Science Assignment Help
Computer Science Assignment Help Computer Science Assignment Help
Computer Science Assignment Help
Programming Homework Help
 
Data Structures and Algorithm: Sample Problems with Solution
Data Structures and Algorithm: Sample Problems with SolutionData Structures and Algorithm: Sample Problems with Solution
Data Structures and Algorithm: Sample Problems with Solution
Programming Homework Help
 
Solving Haskell Assignment: Engaging Challenges and Solutions for University ...
Solving Haskell Assignment: Engaging Challenges and Solutions for University ...Solving Haskell Assignment: Engaging Challenges and Solutions for University ...
Solving Haskell Assignment: Engaging Challenges and Solutions for University ...
Programming Homework Help
 
Exploring Control Flow: Harnessing While Loops in Python
Exploring Control Flow: Harnessing While Loops in PythonExploring Control Flow: Harnessing While Loops in Python
Exploring Control Flow: Harnessing While Loops in Python
Programming Homework Help
 
Design and Analysis of Algorithms Assignment Help
Design and Analysis of Algorithms Assignment HelpDesign and Analysis of Algorithms Assignment Help
Design and Analysis of Algorithms Assignment Help
Programming Homework Help
 
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptxprogramminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
Programming Homework Help
 
Ad

Recently uploaded (20)

Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo SlidesOverview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil DisobediencePaper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdfThe Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke WarnerPublishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Revista digital preescolar en transformación
Revista digital preescolar en transformaciónRevista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
LDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student NewsLDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student News
LDM & Mia eStudios
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptxPEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Rajdeep Bavaliya
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo SlidesOverview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil DisobediencePaper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdfThe Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke WarnerPublishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Revista digital preescolar en transformación
Revista digital preescolar en transformaciónRevista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
LDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student NewsLDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student News
LDM & Mia eStudios
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptxPEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Rajdeep Bavaliya
 
Ad

Java Assignment Sample: Building Software with Objects, Graphics, Containers, and Animation

  • 1. ANIMATE YOUR CODE: JAVA ASSIGNMENT SAMPLES! Programming in Java: Building Software with Objects, Graphics, and Animation
  • 2. Introduction  Objective: Learn how to create and animate graphical objects in Java.  Topics Covered:  Object-Oriented Programming (OOP) in Java  Java’s built-in graphics and containers  Creating and animating shapes  Key Features:  Simple, secure, and robust  Multithreading capabilities  Rich API for building diverse applications
  • 3. Understanding the Classes  SimpleDraw:Manages the window and rendering  Contains the main method  BouncingBox:Represents a box that moves and bounces within the window  DrawGraphics:Manages drawing and animating graphics on the screen
  • 4. In the last assignment you learned how to create your own simple objects. One of the advantages of building software using objects is that it makes it relatively easy to use software components that other people have built. In this assignment, you will use the Java's built-in graphics and containers, combined with a simple framework that we provide. Add three different shapes to the initial window we provide. Requirements: Add three instances of the BouncingBox class to your window, moving in different directions. Use an ArrayList to hold them. Setup: 1.(Optional) Create a new project in Eclipse, with whatever name you want. 2.Create three classes: SimpleDraw, BouncingBox, and DrawGraphics. Copy and paste the code for these classes from below. 3.Run the example program. If Eclipse gives you trouble, open SimpleDraw and run that, as it contains the main method for the program. You should see a window that looks like the following:
  • 5. Part 1: Drawing Graphics Open the DrawGraphics class. The draw method is what draws the contents of the window. Currently, there is a line and a square with a border around it. Feel free to remove these, if you want. Add at least three different shapes to the window. Read the API documentation for the java.awt.Graphics class to find what methods are provided. You can draw rectangles, arcs, lines, text, ovals, polygons, and, if you want to do some extra work, images. Be creative! Note: You should only modify the DrawGraphics class for this step. The other classes contain a bunch of code required to create a window in Java that you do not need to change or understand.
  • 6. Part 2 : Containers & Animations The DrawGraphics class supports animation. The draw method gets called 20 times a second, in order to draw each individual frame. The BouncingBox class also includes animation support. To get the box to move, call setMovementVector method from the DrawGraphics constructor, providing an x and y offset. For example, the value (1, 0) moves the box to the right slowly, while (0, -2) will move it up faster. You only need to call this method once to keep it moving in that direction. In other words, don't call setMovementVector from the draw method, call it from the constructor. Add at least three boxes to your window, moving in different directions. To do this, put three BouncingBox instances in an ArrayList, as part of the DrawGraphics constructor. Then, call the draw method on each of the boxes from DrawGraphics.draw, using a loop. Optional: If you want to experiment, create your own animated object. Copy BouncingBox as a starting point, then edit the code in its draw method. You could create something with more complicated movement, and/or something that looks better than what I created in five minutes. Submission Instructions: Submit your DrawGraphics.java file via Stellar.
  • 8. import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JPanel; /** Displays a window and delegates drawing to DrawGraphics. */ public class SimpleDraw extends JPanel implements Runnable { private static final long serialVersionUID =-7469734580960165754L; private boolean animate = true; private final int FRAME_DELAY = 50; // 50 ms = 20 FPS public static final int WIDTH = 300; public static final int HEIGHT = 300; private DrawGraphics draw; public SimpleDraw(DrawGraphics drawer){ this.draw = drawer;
  • 9. } /** Paint callback from Swing. Draw graphics using g. */ public void paintComponent(Graphics g){ super.paintComponent(g); // Enable anti-aliasing for better looking graphics Graphics2D g2 =(Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); draw.draw(g2); } /** Enables periodic repaint calls. */ public synchronized void start() { animate = true; }
  • 10. /** Pauses animation. */ public synchronized void stop() { animate = false; } private synchronized boolean animationEnabled() { return animate; } public void run() { while (true){ if (animationEnabled()) { repaint(); } try { Thread.sleep(FRAME_DELAY); } catch (InterruptedException e){ throw new RuntimeException(e); }} } public static void main(String args[]) { final SimpleDraw content = new SimpleDraw(new DrawGraphics()); JFrame frame = new JFrame("Graphics!");
  • 11. Color bgColor = Color.white; frame.setBackground(bgColor); content.setBackground(bgColor); // content.setSize(WIDTH, HEIGHT); // content.setMinimumSize(new Dimension(WIDTH, HEIGHT)); content.setPreferredSize(new Dimension(WIDTH, HEIGHT)); // frame.setSize(WIDTH, HEIGHT); frame.setContentPane(content); frame.setResizable(false); frame.pack(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ System.exit(0); } public void windowDeiconified(WindowEvent e){ content.start(); } public void windowIconified(WindowEvent e){ content.stop(); } }); new Thread(content).start(); frame.setVisible(true); } }
  • 13. import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; public class BouncingBox { int x; int y; Color color; int xDirection = 0; int yDirection = 0; final int SIZE = 20; /** * Initialize a new box with its center located at (startX, startY), filled * with startColor. */
  • 14. public BouncingBox(int startX, int startY, Color startColor){ x = startX; y = startY; color = startColor; } /** Draws the box at its current position on to surface. */ public void draw(Graphics surface){ // Draw the object surface.setColor(color); surface.fillRect(x - SIZE/2, y - SIZE/2, SIZE, SIZE); surface.setColor(Color.BLACK); ((Graphics2D) surface).setStroke(new BasicStroke(3.0f)); surface.drawRect(x - SIZE/2, y - SIZE/2, SIZE, SIZE);
  • 15. // If we have hit the edge and are moving in the wrong direction, reverse direction // We check the direction because if a box is placed near the wall, we would get "stuck" // rather than moving in the right direction if ((x - SIZE/2 <= 0 && xDirection < 0) || (x + SIZE/2 >= SimpleDraw.WIDTH && xDirection > 0)) { xDirection =-xDirection; } if ((y - SIZE/2 <= 0 && yDirection < 0) || (y + SIZE/2 >= SimpleDraw.HEIGHT && yDirection > 0)) { yDirection =-yDirection; } } public void setMovementVector(int xIncrement, int yIncrement){ xDirection = xIncrement; yDirection = yIncrement; } } // Move the center of the object each time we draw it x += xDirection; y += yDirection;
  • 16. DrawGraphics.java import java.awt.Color; import java.awt.Graphics; public class DrawGraphics { BouncingBox box; /** Initializes this class for drawing. */ public DrawGraphics() { box = new BouncingBox(200, 50, Color.RED); } /** Draw the contents of the window on surface. Called 20 times per second. */ public void draw(Graphics surface){ surface.drawLine(50, 50, 250, 250); box.draw(surface); } }
  • 18. import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JPanel; /** Displays a window and delegates drawing to DrawGraphics. */ public class SimpleDraw extends JPanel implements Runnable { private static final long serialVersionUID = -7469734580960165754L; private boolean animate = true; private final int FRAME_DELAY = 50; // 50 ms = 20 FPS public static final int WIDTH = 300; public static final int HEIGHT = 300; private DrawGraphics draw;
  • 19. public SimpleDraw(DrawGraphics drawer) { this.draw = drawer; } /** Paint callback from Swing. Draw graphics using g. */ public void paintComponent(Graphics g) { super.paintComponent(g); // Enable anti-aliasing for better looking graphics Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); draw.draw(g2); } /** Enables periodic repaint calls. */ public synchronized void start() { animate = true; } /** Pauses animation. */
  • 20. public synchronized void stop() { animate = false; } private synchronized boolean animationEnabled() { return animate; } public void run() { while (true) { if (animationEnabled()) { repaint(); } try { Thread.sleep(FRAME_DELAY); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
  • 21. public static void main(String args[]) { final SimpleDraw content = new SimpleDraw(new DrawGraphics()); JFrame frame = new JFrame("Graphics!"); Color bgColor = Color.white; frame.setBackground(bgColor); content.setBackground(bgColor); // content.setSize(WIDTH, HEIGHT); // content.setMinimumSize(new Dimension(WIDTH, HEIGHT)); content.setPreferredSize(new Dimension(WIDTH, HEIGHT)); // frame.setSize(WIDTH, HEIGHT); frame.setContentPane(content); frame.setResizable(false); frame.pack(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } public void windowDeiconified(WindowEvent e) { content.start(); } public void windowIconified(WindowEvent e) { content.stop(); } });
  • 22. new Thread(content).start(); frame.setVisible(true); } } import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; public class BouncingBox { int x; int y; Color color; int xDirection = 0; int yDirection = 0; final int SIZE = 20;
  • 23. /** Initialize a new box with its center located at (startX, startY), filled * with startColor. */ public BouncingBox(int startX, int startY, Color startColor) { x = startX; y = startY; color = startColor; } /** Draws the box at its current position on to surface. */ public void draw(Graphics surface) { // Draw the object surface.setColor(color); surface.fillRect(x - SIZE/2, y - SIZE/2, SIZE, SIZE); surface.setColor(Color.BLACK); ((Graphics2D) surface).setStroke(new BasicStroke(3.0f)); surface.drawRect(x - SIZE/2, y - SIZE/2, SIZE, SIZE); // Move the center of the object each time we draw it x += xDirection; y += yDirection;
  • 24. // If we have hit the edge and are moving in the wrong direction, reverse direction // We check the direction because if a box is placed near the wall, we would get "stuck" // rather than moving in the right direction if ((x - SIZE/2 <= 0 && xDirection < 0) || (x + SIZE/2 >= SimpleDraw.WIDTH && xDirection > 0)) { xDirection = -xDirection; } if ((y - SIZE/2 <= 0 && yDirection < 0) || (y + SIZE/2 >= SimpleDraw.HEIGHT && yDirection > 0)) { yDirection = -yDirection; } } public void setMovementVector(int xIncrement, int yIncrement) { xDirection = xIncrement; yDirection = yIncrement; } }
  • 25. import java.awt.Color; import java.awt.Graphics; public class DrawGraphics { BouncingBox box; /** Initializes this class for drawing. */ public DrawGraphics() { box = new BouncingBox(200, 50, Color.RED); } /** Draw the contents of the window on surface. Called 20 times per second. */ public void draw(Graphics surface) { surface.drawLine(50, 50, 250, 250); box.draw(surface); } }
  • 26. Summary: Reviewed Java basics, OOP principles, graphics, containers, and animation Provided sample code and project ideas Next Steps: Experiment with code examples Start building your own Java applications Explore advanced Java topics and libraries Contact Information: For more help and custom programming assignments, visit programminghomeworkhelp.com