How to Draw on the Java Canvas
In this tutorial, we'll explore how to animate an object across a canvas in Java.
You'll learn how to use the Graphics class to draw and move shapes in Java,
specifically a circle, with a simple Java animation example suitable for senior secondary students.
We start by drawing a circle (our body) using the fillOval method of the
Graphics object. This is the foundation for creating a
Java graphics moving object.
Animating a Circle Across the Java Canvas
To animate a circle across canvas in Java, we repeatedly draw the circle,
change its position, and use clearRect() to erase the old image.
This creates a smooth Java Swing animate object effect.
Create a new Java project;
call it Dymetric.
Create 3 new class files; File, New.
Call them Facet, PanelsMovingBody and MovingBody.
Together, they implement the Java canvas animation code.
Type out the adjoining Java code for animating an image body across the canvas component.
How the Java AWT Move Object Animation Code Works
The MovingBody Java class extends Canvas and handles the
actual drawing and movement. It:
- Draws a circle with
fillOval. - Uses
clearRectto erase old drawings. - Updates the
xcoordinate with a loop. - Uses
Thread.sleep()to control speed.
This demonstrates a simple but effective Java animation technique.
What You've Learnt on Java Canvas and Swing Animation
In this tutorial, you've learnt how to animate an object across a canvas in Java. We've used the 'Graphics' class to draw and move shapes in Java, specifically a circle. By repeatedly calling 'repaint()' and using 'Thread.sleep()', we can create a smooth Java animation example.
Key Takeaway on Java Canvas and Swing Animation
By now, you've learned:
- How to move an object across canvas in Java.
- How to use
Graphics,fillOval, andclearRectto create Java GUI animation. - How a repaint loop with
Thread.sleep()achieves smooth motion.
This Java animation example is a foundation for building interactive graphics and games. By now, you should be able to create a simple Java animation example by moving an object across the canvas. This technique is a foundation for more advanced Java GUI animations and games.
So! Java Fun Practice Exercise - Animate Circle
As a fun practice exercise, try changing the speed, direction, or shape. This will help you understand more about Java graphics drawing and updating positions.
Java Moving Body Code - Main Class
public class Dymetric {
public static void main(String[] args) {
Facet lcd = new Facet();
lcd.setVisible(true);
}
}
Java Moving Body Window Setup - Facet Class
import java.awt.*;
import javax.swing.*;
/**
* This class just creates a display window to attach our canvas to.
*/
public class Facet extends JFrame {
public Container face;
public ButtonandCanvasPanels components;
public ImageIcon logo;
public Facet() {
// Give our window a title
super("A window that will hold a Canvas and Button");
// set window start points and dimensions
setSize(780,400);
// close the window when told to
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true); // should this window be resizable?
// It'll be nice to have our own logo (feel free to use yours)
logo = new ImageIcon(getClass().getResource("studyingPays.png"));
this.setIconImage(logo.getImage());
face = this.getContentPane();
// background colour - may not be necessay since our canvas will have a colour of its own
face.setBackground(Color.PINK);
components = new ButtonandCanvasPanels();
// using the default layout manager
face.add(components.button_panel, BorderLayout.NORTH);
// attach appropriate drawing component
face.add(components.canvas_panel, BorderLayout.CENTER);
}
}
Java Moving Body Canvas and Button Controls Class
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class ButtonandCanvasPanels implements ActionListener {
public JPanel button_panel, canvas_panel;
public JButton motion_bttn;
public MovingBody traction;
public ButtonandCanvasPanels() {
button_panel = new JPanel();
// pick a background colour
button_panel.setBackground(Color.PINK);
button_panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
// O my; but for convenience sake let's add our control button here
motion_bttn = new JButton("Glide");
motion_bttn.setBackground(new Color(255, 0, 255));
motion_bttn.addActionListener(this);
// using the default layout manager
button_panel.add(motion_bttn);
canvas_panel = new JPanel();
canvas_panel.setLayout(new BorderLayout());
traction = new MovingBody();
// attach appropriate drawing component
canvas_panel.add(traction, BorderLayout.CENTER);
}
/**
* Respond to the button click event
*/
public void actionPerformed(ActionEvent evt) {
traction.doGlide();
}
}
Java Animation Code - Moving Body Class
import java.awt.*;
public class MovingBody extends Canvas {
protected Color ball_colour;
protected int x = 10;
protected int y = 110;
protected final int aWIDTH, aHEIGHT;
public MovingBody() {
setBackground(Color.LIGHT_GRAY); // canvas color
ball_colour = Color.RED;
aWIDTH = aHEIGHT = 80;
}
public void paint(Graphics g) {
// erase previous circle
g.clearRect(x - 10, y, aWIDTH, aHEIGHT);
g.setColor(ball_colour);
// draw a circle
g.fillOval(x, y, aWIDTH, aHEIGHT);
}
public void doGlide() {
// condition for continuing motion
while (x <= 670) {
paint(this.getGraphics());
x += 10;
// introduce a delay between renderings
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
}
}