Java Mutithreading Ball Animation - java

My issue here with ball animation is that the ball is moving in a straight line leaving behind a trail. My expected output is that there should be no trail of the ball.
The code determines the movement of the ball in just one direction along X axis.
public class App extends JFrame implements Runnable{
int x=0,y=250;
public void run() {
for(;;) {
try {
repaint();
x++;
Thread.sleep(10);
} catch(Exception e){}
}
}
public void paint(Graphics g) {
g.drawOval(x,y,30,30);
}
public static void main(String[] args) {
App frame= new App();
frame.setTitle("Bounce");
frame.setSize(400, 450);
frame.setVisible(true);
Thread t1 = new Thread(frame);
t1.start();
}
}

You missed to call super.paint in your paint method:
public void paint(Graphics g) {
super.paint(g);
g.drawOval(x,y,30,30);
}

This is not a multi-threading issue, you just never "erase" the ovals you draw for the previous x. Your paint method needs to call super.paint() in order to clear the previous ovals. This is explained here with almost the same code as you but without your issue!

Related

How to create new instances of a timer Task instead of canceling and restarting it all over?

Well the thing is that I have a project where I have to make a game on java. In my game there's a spaceship that shoots lasers. I have the mechanics for shooting the laser more or less figured out but I am currently using a timer task to make the laser fly through the JFrame and give the impression a laser was shot.
Problem is that TimerTask seems to bug out as soon as I start shooting many times.
The main goal is to move an object across the screen at a given speed.
Is there something else I could do to achieve this? Is there a better way to implement this?
I appreciate all the help I could get, Thanks.
Here is some of the code:
public Space() {
this.setBackground(Color.BLACK);
this.setCursor(Cursor.getDefaultCursor());
this.addMouseMotionListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
repaint();
x = e.getX()-spaceFighterIcon.getIconHeight()/2;
y = e.getY()-spaceFighterIcon.getIconWidth()/2;
}
public void mouseDragged(MouseEvent e) {
repaint();
x = e.getX()-spaceFighterIcon.getIconHeight()/2; //Positions the cursor on the middle of the spaceShip and viceVersa
y = e.getY()-spaceFighterIcon.getIconWidth()/2;
}
}
);
this.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
if(timerRunning = true){
laserTimer.cancel();
laserTimer.purge();
laserFired = false;
}
if(SwingUtilities.isLeftMouseButton(e)){ // Gets where the laser is going to be shot from
repaint();
laserX = e.getX()-spaceFighterIcon.getIconWidth()/6;
laserY = e.getY();
laserFired = true;
}
if(SwingUtilities.isRightMouseButton(e)){
}
if(SwingUtilities.isMiddleMouseButton(e)){
}
}
});
}
public void paintComponent(Graphics g) {
this.graphics = g;
super.paintComponent(g);
spaceFighterIcon.paintIcon(this, g, x, y);
if(laserFired == true){
shootLaser();
}
}
public void shootLaser(){
laserIcon.paintIcon(this, graphics, laserX, laserY-50); // paints the laser
laserTimer = new Timer();
laserTimer.schedule(new AnimateLasers(), 0, 200); // Timer to move the laser across the frame
timerRunning = true;
repaint();
}
public void lasers(){
laserY = laserY-1; // function to move the laser
if(laserY <= 0){
laserTimer.cancel();
laserTimer.purge();
}
}
public class AnimateLasers extends TimerTask {
public void run() {
lasers();
repaint();
}
}
Start by taking a look at Concurrency in Swing and How to use Swing Timers instead of java.util.Timer.
Swing Timer is safer to use with Swing, as it executes it ticks within the context of the Event Dispatching Thread
Also take a look at Painting in AWT and Swing and Performing Custom Painting for more details about how painting works
Don't maintain a reference to the Graphics context outside of the paint method. Your component will be told when it should repaint it self by the system (via the call to the paintComponent method), essentially, you use the time to update the location of the "laser" and call repaint, then paint the laser within the paintComponent when it's called by the paint system

Drawing a rectangle on screen as an "area selection" tool (Java)

I want the user of my program to be able to highlight an area on a JFrame to select a group of items on screen. The code I posted below works, but it is very choppy, which becomes quite an eyesore every single time the JFrame repaints. Here's an image of what I'm talking about: http://i1065.photobucket.com/albums/u400/mfgravesjr/choppy%20draw%20rectangle_zpsspqsqnyf.png
Maybe someone here has suggestions to improve my code?
This is the mouseDragged method in MouseMotionListener:
public void mouseDragged(MouseEvent me)
{
if(groupingTerr&&me.getSource()==background)
{
endPoint = MouseInfo.getPointerInfo().getLocation();
topLeftRect = new Point(Math.min(startPoint.x,endPoint.x),Math.min(startPoint.y,endPoint.y));
bottomRightRect = new Point(Math.max(startPoint.x,endPoint.x),Math.max(startPoint.y,endPoint.y));
for(Point p:map.territoryPoints)
{
if(p.x>topLeftRect.x&&p.x<bottomRightRect.x&&p.y>topLeftRect.y&&p.y<bottomRightRect.y)img.getGraphics().drawImage(selectedIco,p.x-selectedIco.getWidth()/2,p.y-selectedIco.getHeight()/2,null);
else img.getGraphics().drawImage(defaultIco,p.x-defaultIco.getWidth()/2,p.y-defaultIco.getHeight()/2,null);
}
background.repaint();
}
}
This is the private overridden JFrame class
private static class DrawableJFrame extends JFrame
{
#Override
public void paint(Graphics g)
{
super.paint(g);
g.setColor(new Color(0,0,0,100));
g.drawRect(topLeftRect.x,topLeftRect.y,bottomRightRect.x-topLeftRect.x,bottomRightRect.y-topLeftRect.y);
g.setColor(new Color(200,10,10,100));
g.fillRect(topLeftRect.x,topLeftRect.y,bottomRightRect.x-topLeftRect.x,bottomRightRect.y-topLeftRect.y);
}
}
The image is original artwork. Please do not use it.

Timer of swing not performing as expected

I was suggested not to use sleep for pausing purpose and instead use swing timer but still its not working.The animation i want to achieve is a ball travelling from the top left corner diagonally towards the bottom.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class Show_starter {
int x, y;
JFrame window = new JFrame("Graphic_show");
Graphic_panel jp = new Graphic_panel();
public static void main(String[] args) {
Show_starter start = new Show_starter();
start.go();
}
private void go() {
window.getContentPane().add(BorderLayout.CENTER, jp);
window.setSize(600,800);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class Graphic_panel extends JPanel {
public void paintComponent(Graphics g) {
for ( int i = 0; i < 100; ++i) {
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
x++;
y++;
try {
Timer tmr = new Timer(1000, new TimerListener()); //This fires an event after every 1 sec after it has started by start().
//But The ball travels too much fast and stops at a point and again travels very fast.
tmr.serRepeats(false); // even this is not working.
tmr.start();
//should i use repaint here or in Listener for this timer?
} catch (Exception e){}
}
}
class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
jp.repaint();
}
}
}
}
The behaviour it is showing is very odd ball first goes at very high speed and stops momentarily at a point and again moves at same speed.
I have also tried to change the time for timer event to fire but the same thing happens.
Even inside loop where I have started timer the follow function call is not working
setRepeats(false);
don't create new timers always one timer is enough .decrees timing interval bit more .1 second is too slow for a animation.you don't need a loop and don't increment x and y inside paintcomponet() method because this method get called for some reason for example when you resize,minimize,maximize.
the unexpected behavior is due to your loop and creating new timers(). for example in x y start at zero but in first second x y increased to 100,100 in next paint you see them in a 100,100 position .that's look like quick move and then stop ...
example code (edited)
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Show_starter {
private Timer tmr;
int x, y;
JFrame window = new JFrame("Graphic_show");
Graphic_panel jp = new Graphic_panel();
public static void main(String[] args) {
Show_starter start = new Show_starter();
start.go();
}
private void go() {
window.getContentPane().add(BorderLayout.CENTER, jp);
window.setSize(600, 800);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tmr = new Timer(10, new ActionListener() { // time gap in millisecond
#Override
public void actionPerformed(ActionEvent ae) {
jp.increse();
jp.repaint();
}
});
tmr.start();
}
class Graphic_panel extends JPanel {
public void increse() {
x++;
y++;
if (x > 100) { // stop animation at x>100
tmr.stop();
}
}
public void paintComponent(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
}
}
}
output (smoother than that)
Firstly you should not use a loop inside paint component.
public void paintComponent(Graphics g){
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
}
Just draw it and make x and y public in the class so that you can easily access from outside
Now run a runnable (consult invokelater and swingUtilities) or create a new Thread
inside public void run() do whatever animations you want to do . You can use a loop but add Thread.sleep(//in miliseconds) and repaint() in each iteration .
note : you need to change the x and y and repaint() so that it is drawn in a new position. And the sleep() is needed to slow down the execution otherwise it can't be visible to viewer.

Calling repaint from another class JFrame

I'm trying to call repaint from another class. But it does not work. I have to draw on a frame.
public class Tester extends JFrame{
public static dtest d ;
public static void main(String[] args) {
Tester t = new Tester();
d = new dtest();
test tnew = new test();
}
public static class dtest extends JFrame implements MouseMotionListener{
public static int x,y;
dtest()
{
super("title");
setSize(500,500);
setVisible(true);
addMouseMotionListener(this);
}
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
public void paint(Graphics g)
{
System.out.println("I am called");
}
}
public static class test {
public test()
{
for(int i = 0 ; i < 5 ; i++)
{
System.out.println("I am called from run");
d.repaint();
}
}
}
}
this prints
I am called from run
I am called from run
I am called from run
I am called from run
I am called from run
so it does not executing the paint() portion. d.repaint() is not working. why?
Take a look at this page and look at the first answer. It's a similar if not exact question to yours.
JFrame's paint() method has been deprecated. The compiler, or your IDE, should be complaining a bit, especially if you place the #Override tag directly above the method (use this to test if this method can be rewritten... aka what you're trying to do).
This means that its use has been discouraged and some functionality may have been removed. When using javax.swing, you'll want to learn the system completely about JPanels and JComponents. To paint something on a screen, you'll want to add a custom class that extends JPanel with the add(Component c) method. Then, override the paintComponent(Graphics g) method in that class. Make sure to have the first line in that method be super.paintComponent(g); so that the window can refresh itself.
For completeness:
public class MyWindow extends JFrame {
MyPanel thePanel;
public MyWindow(int x, int y) {
setSize(x, y);
thePanel = new MyPanel(x, y);
this.add(thePanel);
}
}
public class MyPanel extends JPanel {
public MyPanel(int x, int y)
setSize(x, y);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(ImageManager.getImage("Cute Puppy"), 40, 40, null); // Or whatever
}
}
So, when the repaint() or revalidate() method is called on the MyWindow, the Panel will recieve a paintComponent call.
Please let me know in the comments if you need any additional help.
Edited:
Since you need to use MouseMotionListener, and I'm still not quite understanding the context and trouble of "I need to call repaint from another class"... I will try my best.
Firstly, check out this tutorial on the Oracle pages. Also, check out the others on GUI's. You'll learn a lot about organization and displaying that will make you realize how their system can work with yours.
Now, for your questions:
i have to use MouseMotionListener.
Not quite... it is a good way for set up but you can run a Thread (something that constantly runs methods over and over) to check the Mouse coordinates. You'll want to start doing this when you get into games and other miscellaneous applications.
new Thread() {
public void run() {
Point mouse;
int mousex;
int mousey;
while (true) {
mouse = MouseInfo.getPointerInfo().getLocation();
mousex = mouse.x - theWindow.getLocationOnScreen().x - 3; // You'll need to get the
// x coordinate, subtract the window's x coordinate, and subtract 3 because of
// the blue border around a standard pc window.
mousey = mouse.y - theWindow.getLocationOnScreen().y - 29; // 29 is top bar height
SomeOtherClass.processMove(mousex, mousey);
}
}
}.start();
Next: I tried that with JPanel but i could not do that. If you read the tutorial at the top of my edit, you see they implement MouseMotionListener with ease.
Next: I prefer to do it with JFrame. If you wish to process the mouse in the JFrame, do the following: Have your JFrame the listener, but the JPanel be where the mouse data comes from. As follows:
public class MyWindow extends JFrame implements MouseMotionListener {
public MyPanel thePanel;
public int x;
public int y;
public MyWindow() {
thePanel = new MyPanel();
thePanel.addMouseMotionListener(this);
// Make this JFrame get called when the mouse
// moves across the panel.
}
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
thePanel.repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
public class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Other painting stuff
}
}
Next: Now i have to update the frame from another class. I could not find a way to update the GUI(the frame) from another class.
Simple. Since the JPanel is what needs to be updated, add the following method to the MyWindow class:
public void repaintWindow() {
thePanel.repaint();
}
And add this to whenever you need to update it:
MyWindow theWindow = new MyWindow();
theWindow.repaintWindow();
Next: all the answers here extended JPanel. So i could not find my answer.
I apologize, but you NEED a panel. It is possible to do with JFrames, but if you want to start doing things raw and low-level, you need to learn how these things work by learning to read the oracle tutorials and the oracle documentation. For now, use JPanels in any ways I've shown you.
Next: from another class I have to draw something on JFrame.Is that possible?
Yes, indeed! Whenever you want to draw something:
MyWindow theWindow = new MyWindow();
Graphics g = theWindow.thePanel.getGraphics();
BufferedImage someRandomImage = SomeRandomClass.getRandomImage();
g.drawImage(someRandomImage, 200, 481, null);
theWindow.repaintWindow();
I really hope I've helped but to program in java you need to use the tools they give you, especially when it comes to high level things like Swing. There are tutorials everywhere for this stuff. Please read them before asking for specific help in the future.

Java making a ball bounce, its left a trail behind?

Im newish to java, and im writing a pong game.
Ive got the ball to move (Thats my first priority) and make it apear on screen.
But for some Reason its leaving a black line behind it, I dont know if im supposed to errase this or something, but heres the code of my 2 classes (The Ball Class is just a class to save the info of the ball)
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Main extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
public static int Width=650;
public static int Height=600;
public boolean Running=false;
public Thread thread;
public Ball ball = new Ball();
public static void main(String[] args){
Main game = new Main();
JFrame frame = new JFrame();
frame.setSize(Width+25, Height+49);
frame.setTitle("Pong By Poo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.add(game);
game.start();
}
public void start(){
if(Running==true){
return;
} else {
Running=true;
thread = new Thread(this);
thread.start();
}
}
public void run(){
while(Running==true){
try{
Thread.sleep(5);
Draw();
Update();
ball.YVelocity();
ball.XVelocity();
} catch(Exception e){}
}
}
public void Draw(){
BufferStrategy bs = this.getBufferStrategy();
if(bs==null){
createBufferStrategy(2);
} else {
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillOval(ball.BallLocationX, ball.BallLocationY, 20, 20);
g.dispose();
bs.show();
}
}
public void Update(){
if(ball.BallLocationX==0) {
ball.BallMovementX=true;
System.out.println("Ball has hit the Left");
}
if(ball.BallLocationX==Width) {
ball.BallMovementX=false;
System.out.println("Ball has hit the Right");
}
if(ball.BallLocationY==0){
ball.BallMovementY=true;
System.out.println("Ball has hit the Top");
}
if(ball.BallLocationY==Height){
ball.BallMovementY=false;
System.out.println("Ball has hit the bottom");
}
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Ball extends JPanel{
public int BallLocationX;
public int BallLocationY;
public boolean BallMovementY; //true makes the ball go up, false makes it go down
public boolean BallMovementX; //True makes the ball go right, false makes it go left.
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillOval(BallLocationX, BallLocationY, 10, 10);
}
//moves the ball left to right
public int YVelocity(){
if(BallMovementY==true){
BallLocationY++;
} else {
BallLocationY--;
}
return BallLocationY;
}
//Moves the ball up and down
public int XVelocity(){
if(BallMovementX==true){
BallLocationX+=2;
} else {
BallLocationX-=2;
}
return BallLocationX;
}
}
Please help!
Essentially, everywhere your ball moves stays permanently Color.BLACK on your Canvas. If you want to get rid of that, you need to refresh every time the ball moves and repaint the Canvas to Color.WHITE (or whatever) before painting the ball's position again.
Specifically, look at your code here:
public void Draw(){
BufferStrategy bs = this.getBufferStrategy();
if(bs==null){
createBufferStrategy(2);
} else {
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillOval(ball.BallLocationX, ball.BallLocationY, 20, 20);
g.dispose();
bs.show();
}
}
There is no logic here that overwrites your previous changes to the Canvas indicating the ball's location.
Also, as a side nitpick, Java standards are to have method names in camelCase.
And to answer the question in the comments: there is nothing in the Canvas API which automatically understands what you want the default background of the Canvas to be and can reset all other graphics attributes to that. To get this functionality, however, all you'll need to do is repaint your default layout (whether it's all one color, or a basic background image, or anything else) before painting the ball's position on top of it.

Categories