Question: (in Java please) How can i make it Every time the button is pressed the ball is animated, up and down, bouncing like a ball.

(in Java please)

How can i make it Every time the button is pressed the ball is animated, up and down, bouncing like a ball.

The goal of this lab is to use a Thread and get rid of the button. Animate it automatically with a Thread

This is the codes that i have to add on them.

package threadlabexample;

import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel;

public class CanvasPanel extends JPanel implements Runnable{ int x, y; int offset = 25; CanvasPanel() { // Button b = new Button("move"); // b.addActionListener(this); // add(b); x = 50; y = 50; } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.fillOval(x, y, 50, 50); }

@Override public void run() { if(y>420) //logic offset = -25; else if(y < 10) offset = 25; y += offset; repaint(); }

}

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

package threadlabexample;

import java.awt.BorderLayout; import javax.swing.*;

public class ThreadLabExample extends JFrame { CanvasPanel cp; ThreadLabExample() { super("Thread Example"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(500, 500); cp = new CanvasPanel(); getContentPane().add(cp, BorderLayout.CENTER); setVisible(true); } public void animate() { //Thread t = new Thread(cp); //t.start(); } /** * @param args the command line arguments */ public static void main(String[] args) { new ThreadLabExample(); // TODO code application logic here } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!