Java- repaint() alternative - java

Here's my simple code which draws oval near mouse cursor.Each time I click frame is repainted and only one oval can be draw at the time.I would like to know how to make each oval drawn on click to stay on frame.Thank you for each suggestion.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Buffer extends JPanel implements MouseListener{
public static JFrame frame;
public static boolean check;
public void paintComponent(Graphics g){
super.paintComponent(g);
if(check==true){
g.drawOval((int)MouseInfo.getPointerInfo().getLocation().getX(), (int)MouseInfo.getPointerInfo().getLocation().getY(), 10, 10);
}
}
public static void main(String args[]){
Buffer x=new Buffer();
x.setBackground(Color.cyan);
frame=new JFrame();
frame.setSize(500,500);
frame.addMouseListener(x);
frame.add(x);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent e){
check=true;
repaint();
}
public void mouseEntered(MouseEvent arg0){}
public void mouseExited(MouseEvent arg0){}
public void mousePressed(MouseEvent arg0){}
public void mouseReleased(MouseEvent arg0){}
}

Make an ArrayList of objects representing the ovals. In paintComponent, draw each oval in the list. In the mouse listener, add an oval to the list. Here's an example:
public class Buffer extends JPanel implements MouseListener {
...
private List<Ellipse2D> ovals = new ArrayList<Ellipse2D>();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (Ellipse2D oval : ovals)
g2d.draw(oval);
}
public void mouseClicked(MouseEvent e) {
ovals.add(new Ellipse2D.Double(e.getX(), e.getY(), 10, 10);
repaint();
}
}

Related

Draw trail of circles with mouseDragged

I am trying to write a program that draws a line of circles with mouseDragged, like MS paint does. I have successfully gotten my program to draw a circle when I click. I have also been successful in getting my program to draw a circle when I drag the mouse; however, this doesn't leave a line of circles behind wherever I dragged. It simply drags the same circle around. I am trying to get my program to leave a trail of circles behind where I am dragging but I am pretty confused on why my program wont do so.
package assignment_11;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.*;
public class Canvas extends JComponent implements MouseListener, MouseMotionListener{
private int x, x1;
private int y, y1;
public Canvas() {
addMouseMotionListener(this);
addMouseListener(this);
}
public static void main(String[] args) {
//creates new JFrame, sets Exit On Close, sets visible
JFrame window = new JFrame();
window.add(new Canvas());
window.pack();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public Dimension getPreferredSize() {
return new Dimension(640,480);
}
#Override
public void mouseClicked(MouseEvent arg0) {
System.out.println(arg0);
x = arg0.getX();
y = arg0.getY();
repaint();
}
#Override
public void mouseEntered(MouseEvent arg0) {
System.out.println(arg0);
}
#Override
public void mouseExited(MouseEvent arg0) {
System.out.println(arg0);
}
#Override
public void mousePressed(MouseEvent arg0) {
System.out.println(arg0);
}
#Override
public void mouseReleased(MouseEvent arg0) {
System.out.println(arg0);
}
public void paintComponent(Graphics g) {
g.fillOval(x, y, 10, 10);
g.fillOval(x1, y1, 10, 10);
}
#Override
public void mouseDragged(MouseEvent arg0) {
System.out.println(arg0);
x1 = arg0.getX();
y1 = arg0.getY();
repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
System.out.println(arg0);
}
}
Any help is appreciated!
Painting is destructive. That is, every time paintComponent is called, you are expected to repaint the entire state of the component.
This raises the issue - you need some way to store the state you want to paint every time paintComponent is called.
For this, a simple ArrayList would do the job nicely. It would allow you to store all the points you're interested and allow you to repaint them each time paintComponent is called, for example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Canvas extends JComponent implements MouseListener, MouseMotionListener {
private List<Point> points;
public Canvas() {
points = new ArrayList<>(25);
addMouseMotionListener(this);
addMouseListener(this);
}
public static void main(String[] args) {
EventQueue.invokeLater((new Runnable() {
#Override
public void run() {
JFrame window = new JFrame();
window.add(new Canvas());
window.pack();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}));
}
public Dimension getPreferredSize() {
return new Dimension(640, 480);
}
#Override
public void mouseClicked(MouseEvent arg0) {
System.out.println(arg0);
points.add(arg0.getPoint());
repaint();
}
#Override
public void mouseEntered(MouseEvent arg0) {
System.out.println(arg0);
}
#Override
public void mouseExited(MouseEvent arg0) {
System.out.println(arg0);
}
#Override
public void mousePressed(MouseEvent arg0) {
System.out.println(arg0);
}
#Override
public void mouseReleased(MouseEvent arg0) {
System.out.println(arg0);
}
public void paintComponent(Graphics g) {
for (Point p : points) {
g.fillOval(p.x, p.y, 10, 10);
}
}
#Override
public void mouseDragged(MouseEvent arg0) {
System.out.println(arg0);
points.add(arg0.getPoint());
repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
System.out.println(arg0);
}
}
Now, as the complexity of your problem grows, you could instead store "shapes" in the List which have some kind of notion of how to paint themselves, allowing to add in more complex shapes
You should also have a look at Painting in AWT and Swing to gain a better understand of how painting in Swing actually works

The most efficient way to draw a lot of circles java

Ok so I have looked around and I didn't find anything that helped me with this so I thought I would go ahead and ask here. I want to have a bunch of circles that collide bounce and generally interact with each other. The problem I am running into is that drawing a lot of circles eats away at the frame rate. So given an array of circles which I have to draw, all of them. Is the only way to draw them simply to draw them all using g.fillOval() in the paintComponent?
For example, in the paint component, I call a function drawBalls(Graphics2D g) that draws all the balls it contains. (that's how I draw stuff by passing it through to the object that draws I don't know if there is a better way)
for(Ball ball:balls){
ball.drawYourself(g) //g is the Graphics2D
}
Thanks
Edit. Sorry if it was a bad question here is the code of my program. I hope it isn't too long.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import java.util.*;
import javax.swing.Timer;
//###################################################\\
public class Game extends JFrame implements ActionListener{
private Timer myTimer;
private GamePanel panel;
public Game() {
super("Things.py");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1000,800);
panel = new GamePanel(this);
add(panel);
myTimer = new Timer(1, this);
myTimer.start();
setResizable(false);
setVisible(true);
}
public void actionPerformed(ActionEvent evt){
panel.repaint();
}
public static void main(String[] arguments) {
Game frame = new Game();
}
}
//###################################################\\
//###################################################\\
class GamePanel extends JPanel implements MouseMotionListener, MouseListener,KeyListener{
// ------------ Variables ----------------------------------------------
private int mx,my;//Mouse position x and y
private boolean[]keys;//If the keys are pressed
private Boolean mousepressed=false;//If the mouse is pressed down
private Game mainframe;//The panel that created this GamePanel
private Color backmenuc;
private Color backcolor;
private bounceBalls bballs;
private bounceBalls bballs2;
// ------------ Constructor --------------------------------------------
public GamePanel(Game m){
//----- Listeners -----
addMouseMotionListener(this);//LISTEN TO ME!!!
addMouseListener(this);//Listen to me!
addKeyListener(this);//listen to me pls
//----- Variables -----
mainframe=m;
keys=new boolean[KeyEvent.KEY_LAST+1];//creates the array for keys
backcolor=new Color(0,0,0);
backmenuc=new Color(255,255,255);
bballs=new bounceBalls(this);
bballs2=new bounceBalls(this);
//----- Load Images -----
//----- End -----
}
// ------------ Drawing ------------------------------------------------
public void paintComponent(Graphics gg){
Graphics2D g=(Graphics2D) gg;
paint.drawRect(g,0,0,getWidth(),getHeight(),backcolor);
if (mousepressed){
bballs.addBall(mx,my,10);
bballs2.addBall(mx+100,my,10);
}
bBallThreading b1=new bBallThreading(g,bballs,"B1");
b1.start();
bBallThreading b2=new bBallThreading(g,bballs2,"B1");
b2.start();
//bballs.update();
//bballs2.update();
bballs.draw(g);
bballs2.draw(g);
System.out.println(bballs.size());
}
// ------------ Misc ---------------------------------------------------
public void addNotify() {
super.addNotify();
}
// ------------ MouseListener ------------------------------------------
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {
mousepressed=false;
}
public void mouseClicked(MouseEvent e){
}
public void mousePressed(MouseEvent e){
mousepressed=true;
}
// ---------- MouseMotionListener --------------------------------------
public void mouseDragged(MouseEvent e){
mx=e.getX();
my=e.getY();
}
public void mouseMoved(MouseEvent e){
mx=e.getX();
my=e.getY();
}
// ---------- KeyListener -----------------------------------------------
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
}
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}
}
//###################################################\\
class bounceBall{
private double bx,by;
private int br;
private double vx,vy;
public bounceBall(int x,int y,int radius){
bx=(double)x;
by=(double)y;
br=radius;
vx=0;
vy=0;
}
public void move(){
if((by+vy)>800){
vy*=-.9;
}
bx+=vx;
by+=vy;
}
public void addV(double x, double y){
vx+=x;
vy+=y;
}
public void draw(Graphics2D g){
g.setColor(new Color(255,0,0));
g.fillOval((int)bx-br,(int)by-br,br*2,br*2);
}
}
class bounceBalls{
GamePanel gp;
ArrayList<bounceBall> balls;
double gravity;
public bounceBalls(GamePanel gamep){
gp=gamep;
gravity=.1;
balls=new ArrayList<bounceBall>();
}
public void draw(Graphics2D g){
//paint.setAA(g,true);
paint.setAlpha(g,.1f);
for(bounceBall ball:balls.toArray(new bounceBall[balls.size()])){
ball.draw(g);
}
paint.setAlpha(g,1f);
//paint.setAA(g,false);
}
public void setGravity(double g){
gravity=g;
}
public void update(){
for(bounceBall ball:balls.toArray(new bounceBall[balls.size()])){
ball.addV(0,gravity);
ball.move();
}
}
public void addBall(int x, int y, int radius){
balls.add(new bounceBall(x,y,radius));
}
public int size(){
return balls.size();
}
}
class bBallThreading implements Runnable{
private Thread t;
private String threadname;
Graphics2D g;
private bounceBalls bballs;
public bBallThreading(Graphics2D g, bounceBalls bballs,String s){
this.g=g;
this.bballs=bballs;
threadname=s;
}
public void run(){
bballs.update();
}
public void start(){
if (t == null)
{
t = new Thread (this, threadname);
t.start ();
}
}
}
//###################################################\\
When I run this I get 4000 circles at 30 fps
bBallThreading b1=new bBallThreading(g,bballs,"B1");
b1.start();
bBallThreading b2=new bBallThreading(g,bballs2,"B1");
b2.start();
The paintComponent() method is for painting. That is all is should do.
You should NOT be starting a Thread in a painting method. Every time Swing paints the component you will be starting two more Threads.
Add a System.out.println(...) statement to that method to see how many times that method is executed.
You should start the Thread when you start the animation.

Why doesn't this Java paint program paint more than one oval?

I have a Java paint program that uses a custom JPanel to paint on. While when clicking on the JPanel paints a small oval (or circle, if you will), the oval disappears each time you click on another place. The coordinates also get updated, but the oval does not stay, it moves to wherever the user clicks next...
Here's the code for the custom JPanel:
int xCord, yCord;
public class PaintPanel extends JPanel implements MouseListener {
// default serial whatever...
private static final long serialVersionUID = -6514297510194472060L;
// initial values
int xCord = -10;
int yCord = -10;
public PaintPanel() {
addMouseListener(this);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(ProgramUI.currentColor);
g.fillOval(xCord, yCord, 8, 8);
repaint();
}
#Override
public void mouseClicked(MouseEvent m) {
}
#Override
public void mouseEntered(MouseEvent m) {
}
#Override
public void mouseExited(MouseEvent m) {
}
#Override
public void mousePressed(MouseEvent m) {
if (paintPanel.contains(m.getPoint())) {
xCord = m.getX();
yCord = m.getY();
System.out.println("x: " + xCord + " y: " + yCord);
}
}
#Override
public void mouseReleased(MouseEvent m) {
}
}
I need the holding of a mouse to continuously paint an oval until the mouse button is let go. The only problem here is that the mouse oval updates, but does not save it's original position. How do I fix this?
Only one oval is drawn as there is only one fillOval statement drawing a single oval in the paintComponent method so the statement
super.paintComponent(g);
causes any previous painting to be cleared once repaint is called.
To paint multiple ovals, you can paint components from a List<Point> as outlined in Custom Painting Approaches
Don't call repaint from within paintComponent. This creates an infinite loop and degrades performance. If periodic updates are required invoke repaint from the ActionListener of a Swing Timer instead.
that is because the component repaints itself, to make the change permanent you should take the image of the jpanel and set it as background once you finish drawing each time...
You are only painting the last place the user clicked each time. Instead, you need to collect the past clicks and paint them all each time.
This code will do what you want:
package com.sandbox;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
public class SwingSandbox {
public static void main(String[] args) {
JFrame frame = buildFrame();
frame.add(new PaintPanel());
}
public static class PaintPanel extends JPanel implements MouseListener {
// default serial whatever...
private static final long serialVersionUID = -6514297510194472060L;
ArrayList<Point> points = new ArrayList<Point>();
public PaintPanel() {
addMouseListener(this);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(250));
for (Point point : points) {
g.fillOval(point.x, point.y, 8, 8);
}
repaint();
}
#Override
public void mouseClicked(MouseEvent m) {
}
#Override
public void mouseEntered(MouseEvent m) {
}
#Override
public void mouseExited(MouseEvent m) {
}
#Override
public void mousePressed(MouseEvent m) {
if (this.contains(m.getPoint())) {
points.add(m.getPoint());
}
}
#Override
public void mouseReleased(MouseEvent m) {
}
}
private static JFrame buildFrame() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
return frame;
}
}

Multiple problems regarding Java paint program while painting

I have a Java paint program, and I've got two problems to do with it. Both problems are relatively simple, and just regard how the mouse input is handled and how the image uses colors. Here's a photo of the app:
So here's my first problem:
As you can see, by the look of the app, there's a spray of dots on the paint area. Each of those dots is a mouseclick. The program does not recognize when a user is holding down the mouse button, so you have to click individually.
This is obviously counterproductive, user-unfriendly and unacceptable. Now, how I fix this, I'm not sure. I've tried using a permanent while (true) loop, but that does not work. How do I make it so that instead of having to click every time, each time the mouse is held down it sprays out dots?
The second problem is the color of the dots. As you can see, at the bottom, there are color buttons. These function, but there is a problem: Whenever I change the color, all the dots currently on the screen change color. The color is run by a variable called currentColor which is run by the actionListeners controlled by all the color buttons on the bottom panel. How do I make sure that colors already placed on the screen are not affected anymore?
I believe that all the code that can be fixed for these two problems lies in my custom JPanel which is used for the program to paint on. I'll post the entire class below, and if you have any other questions, please let me know.
int xCord, yCord;
public class PaintPanel extends JPanel implements MouseListener {
// default serial whatever...
private static final long serialVersionUID = -6514297510194472060L;
public PaintPanel() {
addMouseListener(this);
}
ArrayList<Point> points = new ArrayList<Point>();
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Point point : points) {
g.setColor(currentColor);
g.fillOval(point.x, point.y, 12, 12);
}
repaint();
}
#Override
public void mouseClicked(MouseEvent m) {
}
#Override
public void mouseEntered(MouseEvent m) {
}
#Override
public void mouseExited(MouseEvent m) {
}
#Override
public void mousePressed(MouseEvent m) {
if (paintPanel.contains(m.getPoint())) {
points.add(m.getPoint());
xCord = m.getX();
yCord = m.getY();
System.out.println("x: " + xCord + " y: " + yCord);
}
}
#Override
public void mouseReleased(MouseEvent m) {
}
}
Painting in Swing is destructive.
That is to say, when Swing requests that a repaint occur on a component, the component is expected to clear what ever was previously paint and update itself.
The problem with your color issue is that you only ever have a single color specified.
A possible solution would be to paint to backing buffer (like BufferedImage) instead of relying on paintComponent.
Instead of repainting all the dots each time paintComponent is called, you would simply paint the BufferedImage instead.
As to your issue with the mouse, you need to implement a MouseMotionListener, this will allow you to detect when the mouse is dragged across the surface, painting a trail of dots
Update with very BASIC example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SimplePaint04 {
public static void main(String[] args) {
new SimplePaint04();
}
public SimplePaint04() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private PaintPane paintPane;
public TestPane() {
setLayout(new BorderLayout());
add((paintPane = new PaintPane()));
add(new ColorsPane(paintPane), BorderLayout.SOUTH);
}
}
public class ColorsPane extends JPanel {
public ColorsPane(PaintPane paintPane) {
add(new JButton(new ColorAction(paintPane, "Red", Color.RED)));
add(new JButton(new ColorAction(paintPane, "Green", Color.GREEN)));
add(new JButton(new ColorAction(paintPane, "Blue", Color.BLUE)));
}
public class ColorAction extends AbstractAction {
private PaintPane paintPane;
private Color color;
private ColorAction(PaintPane paintPane, String name, Color color) {
putValue(NAME, name);
this.paintPane = paintPane;
this.color = color;
}
#Override
public void actionPerformed(ActionEvent e) {
paintPane.setForeground(color);
}
}
}
public class PaintPane extends JPanel {
private BufferedImage background;
public PaintPane() {
setBackground(Color.WHITE);
setForeground(Color.BLACK);
MouseAdapter handler = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
drawDot(e.getPoint());
}
#Override
public void mouseDragged(MouseEvent e) {
drawDot(e.getPoint());
}
};
addMouseListener(handler);
addMouseMotionListener(handler);
}
protected void drawDot(Point p) {
if (background == null) {
updateBuffer();;
}
if (background != null) {
Graphics2D g2d = background.createGraphics();
g2d.setColor(getForeground());
g2d.fillOval(p.x - 5, p.y - 5, 10, 10);
g2d.dispose();
}
repaint();
}
#Override
public void invalidate() {
super.invalidate();
updateBuffer();
}
protected void updateBuffer() {
if (getWidth() > 0 && getHeight() > 0) {
BufferedImage newBuffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = newBuffer.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, getWidth(), getHeight());
if (background != null) {
g2d.drawImage(background, 0, 0, this);
}
g2d.dispose();
background = newBuffer;
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (background == null) {
updateBuffer();
}
g2d.drawImage(background, 0, 0, this);
g2d.dispose();
}
}
}

Painting Ellipses in Java

I have a java program which displays an ellipse on the screen and changes its direction through the use of the arrow keys. I constantly call repaint() on the ellipse using a while loop.
The ellipse moves, but the problem is that it leaves a trail of ellipses on its path. How do I make it so that it removes the old ellipses and then repaint the new one?
Code:
public void run(){
while (animator != null)
{
setBackground(Color.GREEN);
repaint();
// The direction works and the rest works fine.
player1.move(player1, player1.direction);
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
break;
}
}
}
// The paintComponent of my player1 is fine.
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D)g;
player1.paintComponent(g2, player1);
}
The problem is likely that your paintComponent(Graphics) overriden method is not calling super.paintComponent(g), which clears the canvas, among other things:
// Bad:
#Override
public void paintComponent(Graphics g) {
// paint the ellipse, etc.
}
// Good:
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// paint the ellipse, etc.
}
Here is some basic code which does the very basics (without the use of a continuous while loop):
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class Ellipses extends JFrame {
public static void main(String[] args){
//Ensures application is not run on the main thread
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Ellipses myEllipses = new Ellipses();
myEllipses.init();
}
});
}
public Ellipses(){
//Set up the frame
this.setTitle("Ellipses Example");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setSize(400, 400);
}
private Ellipse ellipse1;
public void init(){
Container contentPane = this.getContentPane();
//Create a new ellipse and add to the content pane
ellipse1 = new Ellipse();
contentPane.add(ellipse1);
//Add the keyListener to the contentPane
contentPane.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP){
ellipse1.decreaseY();
}
if(e.getKeyCode() == KeyEvent.VK_DOWN){
ellipse1.increaseY();
}
if(e.getKeyCode() == KeyEvent.VK_LEFT){
ellipse1.decreaseX();
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
ellipse1.increaseX();
}
//Repaint the ellipse
ellipse1.repaint();
}
});
//Request the focus so key presses can be detected
contentPane.setFocusable(true);
contentPane.requestFocus();
}
//Create an ellipse which can be drawn to the screen
public class Ellipse extends JComponent{
private int x , y; //Coordinates of the oval
public Ellipse(){
setCoordinates(100, 100);
}
public void setCoordinates(int x, int y){
this.x = x;
this.y = y;
}
public void increaseY(){
y+=10;
}
public void increaseX(){
x+=10;
}
public void decreaseY(){
y-=10;
}
public void decreaseX(){
x-=10;
}
public void paint(Graphics g){
//Ensures previous paint is cleared
super.paintComponents(g);
g.setColor(Color.RED);
g.fillOval(x, y, 100, 100);
}
}
}
You should draw the background Color before drawing the ellipse in the game loop :)
Also you can call repaint() , it actually calls update() to do
the dirty work of clearing the screen and calling paint().
When you use repaint the update method inherit
public void update(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, width, height);
g.setColor(getForeground());
paint(g)
}
so the background return to it's original color and the trail of ellipses will be removed

Categories