Im working on an assignment where an image moves around and when the user clicks on the panel the image stops. When the user clicks on the panel again the image starts. As of now i can only start and stop the image once before it stays going. I need help to loop this process so that the user can keep starting and stopping the image.
Here is my code
Main:
import javax.swing.*;
public class Rebound {
//-----------------------------------------------------------------
// Displays the main frame of the program.
//-----------------------------------------------------------------
public static void main (String[] args)
{
JFrame frame = new JFrame ("Rebound");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReboundPanel());
frame.pack();
frame.setVisible(true);
}
}
Panel:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ReboundPanel extends JPanel
{
private final int DELAY = 10, IMAGE_SIZE = 35;
private ImageIcon image;
private Timer timer;
private int x, y, moveX, moveY;
public ReboundPanel()
{
timer = new Timer(DELAY, new ReboundListener());
addMouseListener (new StopListener());
image = new ImageIcon ("happyFace.gif");
x = 0;
y = 40;
moveX = moveY = 3;
setPreferredSize (new Dimension(1900, 1000));
setBackground (Color.black);
timer.start();
}
public void paintComponent (Graphics page)
{
super.paintComponent (page);
image.paintIcon (this, page, x, y);
}
private class ReboundListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
x += moveX;
y += moveY;
if (x <= 0 || x >= 1900-IMAGE_SIZE)
moveX = moveX * -1;
if (y <= 0 || y >= 1000-IMAGE_SIZE)
moveY = moveY * -1;
repaint();
}
}
// Represents the action listener for the timer.
public class StopListener extends MouseAdapter
{
public void mouseClicked (MouseEvent event)
{
if (event.getButton() == MouseEvent.BUTTON1)
{
timer.stop();
}
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
if(event.getButton() == MouseEvent.BUTTON1)
{
timer.start();
removeMouseListener(this);
}
}
});
}
}
}
You can simply reuse the same listener, and check the state of the timer before starting/stopping it:
public void mouseClicked(MouseEvent event)
{
if (event.getButton() == MouseEvent.BUTTON1)
{
if (timer.isRunning()) {
timer.stop();
}
else {
timer.start();
}
}
}
In you StopListener class have an instance variable bool isMoving = true;
Then in your handler should use that to determine whether to stop or start the timer:
public void mouseClicked( MouseEvent event )
{
if( event.getButton() == MouseEvent.BUTTON1 )
{
if( isMoving )
timer.stop();
else
timer.start();
isMoving = !isMoving;
}
}
Related
Form some reason when it switches Icon's the image flashes. I'm also having this problem even more when I try to create objects then try to make them move by passing the x and y through as parameters on the object. Any help would be great.
public class Main extends JFrame implements ActionListener, KeyListener{
static Main main;
Render render;
Timer timer;
static int x,y,count;
ImageIcon player1 = new ImageIcon("C:\\Users\\Kyle\\Documents\\NetBeansProjects\\Testing52\\src\\testing52\\Player1.png");
ImageIcon player2 = new ImageIcon("C:\\Users\\Kyle\\Documents\\NetBeansProjects\\Testing52\\src\\testing52\\Player2.png");
Main(){
render = new Render();
timer = new Timer(100,this);
setVisible(true);
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
addKeyListener(this);
add(render);
timer.start();
}
public void render(Graphics g){
count += 1;
if(count < 20){
player1.paintIcon(this, g, x, y);
}
if(count > 20){
player2.paintIcon(this, g, x, y);
}
if(count > 40){
count = 0;
}
}
public static void main(String [] args){
main = new Main();
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(count);
render.repaint();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int id = e.getKeyCode();
int speed = 4;
if(id == KeyEvent.VK_UP){
y -= speed;
}
if(id == KeyEvent.VK_DOWN){
y += speed;
}
if(id == KeyEvent.VK_LEFT){
x -= speed;
}
if(id == KeyEvent.VK_RIGHT){
x += speed;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
}
Render class.
public class Render extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
Main.main.render((Graphics)g);
}
}
Another thing that could make your animation smoother is if you called revalidate() in your action event after repaint().
The happy face Im using----)This project wants me to Modify the Rebound program from this chapter such that when the mouse button is clicked the animation stops, and when its clicked again the animation resumes.
When I click on the screen with the moving smiley face, it doesnt stop when I click it nor start up again because I couldnt stop the smiley face from moving What am I doing wrong? Here is the problem area.------) |
private class ReboundMouseListener implements MouseListener {
public void mouseClicked(MouseEvent event) {
if (timer.isRunning())
timer.stop();
else
timer.start();
}
}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
public void mousePressed(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}
}
Here is the rest of the code:
public class ReboundPanel extends JPanel {
private final int WIDTH =300, HEIGHT= 100;
private final int DELAY= 20, IMAGE_SIZE=35;
private ImageIcon image;
private Timer timer;
private int x, y, moveX, moveY;
//---------------------------------------------------------
// Sets up the panel,including the timer for the animation.
//---------------------------------------------------------
public ReboundPanel(){
timer= new Timer(DELAY, new ReboundListener());
image= new ImageIcon("happyFace.gif");
x=0;
y=40;
moveX=moveY=3;
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.black);
timer.start();
}
//---------------------------------------------------------
// Draws the image in the current location.
//---------------------------------------------------------
public void paintComponent(Graphics page)
{
super.paintComponent(page);
image.paintIcon(this, page, x, y);
}
//*********************************************************
// Represents the action listener for the timer.
//*********************************************************
private class ReboundListener implements ActionListener
{
//--------------------------------------------------------
// Updates the position of the image and possibly the direction
// of movement whenever the timer fires an action event.
//--------------------------------------------------------
public void actionPerformed(ActionEvent event)
{
x += moveX;
y += moveY;
if (x <=0 || x >= WIDTH-IMAGE_SIZE)
moveX =moveX * -1;
if (y <=0 || y >= HEIGHT-IMAGE_SIZE)
moveY = moveY * -1;
repaint();
}
}
private class ReboundMouseListener implements MouseListener {
//--------------------------------------------------------------
// Stops or starts the timer (and therefore the animation)
// when the mouse button is clicked.
//--------------------------------------------------------------
public void mouseClicked(MouseEvent event) {
if (timer.isRunning())
timer.stop();
else
timer.start();
}
//--------------------------------------------------------------
// Provide empty definitions for unused event methods.
//--------------------------------------------------------------
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
public void mousePressed(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}
}
}
public class Rebound {
public static void main(String[] args) {
JFrame frame = new JFrame("Rebound");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReboundPanel());
frame.pack();
frame.setVisible(true);
}
}
Looks like you are missing your addMouseListener() calls:
public ReboundPanel() {
// Other initializations ...
addMouseListener(new ReboundMouseListener()); // <-- add
timer.start();
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MovingCircleGUI
{
JFrame frame;
public int x,y;
public int vx = 30,vy=20;
public int width = 500,height = 500;
public int diameter=100;
CircleDrawPanel drawPanel;
Color color = Color.magenta.darker();
JButton button;
Timer timer2 = new Timer(10, new AnimateCircleListener());
boolean isRunning = false;
public static void main (String[] args)
{
MovingCircleGUI gui = new MovingCircleGUI();
gui.go();
}
//this method sets up the JFrame and adds the draw panel to the frame
public void go()
{
frame = new JFrame("MovingCircleGUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawPanel = new CircleDrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
button = new JButton("Click me to start the animation");
drawPanel.add(button);
frame.getContentPane().add(BorderLayout.SOUTH , button);
button.addActionListener(new AnimateCircleListener());
frame.setSize(width,height);
frame.setVisible(true);
}
class CircleDrawPanel extends JPanel
{
public void paintComponent (Graphics g)
{
super.paintComponent(g);
Graphics2D g2=(Graphics2D)g;
g2.setColor(color);
g2.fillOval(x,y,diameter,diameter);
}
}
public void MovingBall()
{
x = x + vx;
y = y + vy;
if( y >= height)
{
y=0;
boolean xIsSame = true;
int randomX = 0;
do
{
randomX = Math.round((float)Math.random()*width);
if (randomX != x)
{
x = randomX;
}
}
while(!xIsSame);
}
if(x <= 0)
{
x = width+x;
}
if (x >= width)
{
x = x-width;
}
timer2.start();
frame.repaint();
}
class AnimateCircleListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== button)
{
if(isRunning)
{
isRunning = false;
button.setText("Click me to start the animation");
button.revalidate();
}
else
{
isRunning = true;
MovingBall();
button.setText("Click me to stop the animation");
button.revalidate();
}
}
}
}
public int getX()
{
return x;
}
public void setX(int x)
{
this.x = x;
}
public int getY()
{
return y;
}
public void setY(int y)
{
this.y = y;
}
}
I am trying to construct a one button which handles two events mainly to start and stop the animation. What I am trying to do is when the user clicks the button the animation of the bouncing ball will start, and the text of the button will change to "Click me to stop", and when the user clicks the button again the animation will stop. I am using the timer.
The animation is okay, I worked that out, and that when the user clicks the button, the animation start that's okay too. The only problem I've got is how am I going to handle another event to the same button?
You could do something similar to this. This way you only need one Action Listener and a boolean to tell it which action to do.
boolean isRunning = false
button.addActionListener(new YourActionListener());
public class YourActionListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button)
{
if(isRunning)
{
isRunning = false;
button.setText("Click me to start");
button.revalidate();
}
else
{
isRunning = true;
button.setText("Click me to stop");
button.revalidate();
}
}
}
}
Edit
Your code now works. What you wanted to do was call the MoveBall method when timer2 fired the Action Listener.
This can be done by
if(e.getSource()==timer2)
{
MovingBall();
}
so in your code it would look like.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MovingCircleGUI
{
JFrame frame;
public int x,y;
public int vx = 10,vy=5;
public int width = 500,height = 500;
public int diameter=50;
CircleDrawPanel drawPanel;
Color color = Color.magenta.darker();
JButton button;
Timer timer2 = new Timer(25, new AnimateCircleListener());
boolean isRunning = false;
public static void main (String[] args)
{
MovingCircleGUI gui = new MovingCircleGUI();
gui.go();
}
//this method sets up the JFrame and adds the draw panel to the frame
public void go()
{
frame = new JFrame("MovingCircleGUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawPanel = new CircleDrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
button = new JButton("Click me to start the animation");
drawPanel.add(button);
frame.getContentPane().add(BorderLayout.SOUTH , button);
button.addActionListener(new AnimateCircleListener());
frame.setSize(width,height);
frame.setVisible(true);
}
class CircleDrawPanel extends JPanel
{
public void paintComponent (Graphics g)
{
super.paintComponent(g);
Graphics2D g2=(Graphics2D)g;
g2.setColor(color);
g2.fillOval(x,y,diameter,diameter);
}
}
public void MovingBall()
{
x = x + vx;
y = y + vy;
if( y >= height)
{
y=0;
boolean xIsSame = true;
int randomX = 0;
do
{
randomX = Math.round((float)Math.random()*width);
if (randomX != x)
{
x = randomX;
}
}
while(!xIsSame);
}
if(x <= 0)
{
x = width+x;
}
if (x >= width)
{
x = x-width;
}
frame.repaint();
}
class AnimateCircleListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== button)
{
if(timer2.isRunning())
{
button.setText("Click me to start the animation");
button.revalidate();
timer2.stop();
}
else
{
button.setText("Click me to stop the animation");
button.revalidate();
timer2.start();
}
}
if(e.getSource()==timer2)
{
MovingBall();
}
}
}
public int getX()
{
return x;
}
public void setX(int x)
{
this.x = x;
}
public int getY()
{
return y;
}
public void setY(int y)
{
this.y = y;
}
}
You can remove the previous ActionListener on the JButton using button.removeActionListener(<your first action listener>) and then add the second action listener using button.addActionListener(<your second action listener>). Then, to change the text on the button, just use button.setText("Your Text Here").
I'm trying to make a kind of brickbreaker game but once I press the start button ("starten" = true). I can't use the keyPressed()-utility anymore but before i pressed the start button I could use the keyPressed()-utility. Could somebody please tell me why I suddenly can't use the keyPressed()-utility anymore and give me a possible solution too?
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class VGKernel extends JPanel implements KeyListener {
public Rectangle screen, ball, block; // The screen area and ball location/size.
public Rectangle bounds; // The boundaries of the drawing area.
public JFrame frame; // A JFrame to put the graphics into.
public VGTimerTask vgTask; // The TimerTask that runs the game.
public boolean down, right, starten = false; // Direction of ball's travel.
public JButton start;
public VGKernel(){
super();
screen = new Rectangle(0, 0, 600, 400);
ball = new Rectangle(0, 0, 20, 20);
block = new Rectangle(260, 350, 40, 10);
bounds = new Rectangle(0, 0, 600, 400); // Give some starter values.
frame = new JFrame("VGKernel");
vgTask = new VGTimerTask();
addKeyListener(this);
setFocusable(true);
start = new JButton("Start");
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
starten = true;
}
});
add(start);
}
class VGTimerTask extends TimerTask{
public void run(){
repaint();
if(starten){
moveBall();
frame.repaint();
}
}
}
// Now the instance methods:
public void paintComponent(Graphics g){
// Get the drawing area bounds for game logic.
bounds = g.getClipBounds();
// Clear the drawing area, then draw the ball.
g.clearRect(screen.x, screen.y, screen.width, screen.height);
g.fillRect(ball.x, ball.y, ball.width, ball.height);
g.fillRect(block.x, block.y, block.width, block.height);
}
public void moveBall(){
// Ball should really be its own class with this as a method.
if (right) ball.x+=1; // If right is true, move ball right,
else ball.x-=1; // otherwise move left.
if (down) ball.y+=1; // Same for up/down.
else ball.y-=1;
if (ball.x > (bounds.width - ball.width)) // Detect edges and bounce.
{ right = false; ball.x = bounds.width - ball.width; }
if (ball.y > (bounds.height - ball.height))
{ down = false; ball.y = bounds.height - ball.height;}
if (ball.x == 0) { right = true; ball.x = 0; }
if (ball.y == 0) { down = true; ball.y = 0; }
}
public void keyPressed(KeyEvent evt) {
if(evt.getKeyCode() == KeyEvent.VK_G && block.x > 0) {
block.x -= 20;
}
if(evt.getKeyCode() == KeyEvent.VK_H && block.x < 540) {
block.x += 20;
}
}
public void keyTyped(KeyEvent evt){ }
public void keyReleased(KeyEvent evt){ }
public void startActionPerformed(java.awt.event.ActionEvent evt) {
starten = true;
}
public static void main(String arg[]){
java.util.Timer vgTimer = new java.util.Timer(); // Create a Timer.
VGKernel panel = new VGKernel(); // Create and instance of our kernel.
// Set the intial ball movement direction.
panel.down = true;
panel.right = true;
// Set up our JFRame
panel.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.frame.setSize(panel.screen.width, panel.screen.height);
panel.frame.setContentPane(panel);
panel.frame.setVisible(true);
// Set up a timer to do the vgTask regularly.
vgTimer.schedule(panel.vgTask, 0, 10);
}
}
You need to make sure whatever component you're listening for KeyEvents on has the focus.
Once you click the button, that button has focus instead of your JPanel. More info here: http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html
You can use the requestFocusInWindow() method on your JPanel, or you can call setFocusable(false) on your JButton.
Or you could use key bindings instead: http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
Add VGKernel.this.grabFocus(); to the ActionListener to return focus to the VGKernel panel after clicking the button.
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
starten = true;
VGKernel.this.grabFocus();
}
});
The problem is that this ball after it is dragged and exited click, it is supposed to repaint according to the new y component given. This is calculated from the gravity final and added to the velocity which is added to the existing y component in a loop.
I have debugged many times and I just cant hit it on the head.
Its supposed to..
move to where you drag it >>> when you let go it is supposed to fall until it hits the ground.
Thank you ahead of time.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DragBallPanel extends JPanel implements MouseListener, MouseMotionListener
{
private static final int BALL_DIAMETER = 40;
private int screen_size_x = 300;
private int screen_size_y = 300;
private int ground_lvl = screen_size_y - 15;
private int _ballX = ground_lvl/2;
private int _ballY = ground_lvl - BALL_DIAMETER;
private final double GRAVITY = -9.8;
private double velocity;
private static final double TERM_VEL = -100;
private int _dragFromX = 0;
private int _dragFromY = 0;
private boolean _canDrag = false;
public DragBallPanel() throws InterruptedException
{
setPreferredSize(new Dimension(screen_size_x, screen_size_y));
setBackground(Color.darkGray);
setForeground(Color.darkGray);
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g); // Required for background.
g.setColor (Color.green);
g.fillRect (0, 280, 400, 50 );
g.setColor (Color.black);
g.fillOval(_ballX, _ballY, BALL_DIAMETER, BALL_DIAMETER);
}
public void mousePressed(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
if (x >= _ballX && x <= (_ballX + BALL_DIAMETER)
&& y >= _ballY && y <= (_ballY + BALL_DIAMETER))\
{
_canDrag = true;
_dragFromX = x - _ballX;
_dragFromY = y - _ballY;
} else
{
_canDrag = false;
}
}
//===== mouseDragged ======
/** Set x,y to mouse position and repaint. */
public void mouseDragged(MouseEvent e)
{
if (_canDrag)
{ // True only if button was pressed inside ball.
//--- Ball pos from mouse and original click displacement
_ballX = e.getX() - _dragFromX;
_ballY = e.getY() - _dragFromY;
//--- Don't move the ball off the screen sides
_ballX = Math.max(_ballX, 0);
_ballX = Math.min(_ballX, getWidth() - BALL_DIAMETER);
//--- Don't move the ball off top or bottom
_ballY = Math.max(_ballY, 0);
_ballY = Math.min(_ballY, getHeight() - BALL_DIAMETER);
this.repaint();
}
}
public void mouseExited(MouseEvent e)
{
while(_ballY < ground_lvl)
{
simulateGravity();
}
}
public void simulateGravity()
{
if(_canDrag)
{
try{
velocity = velocity + GRAVITY;
if (velocity < TERM_VEL)
{
velocity = TERM_VEL;
}
if (_ballY >= ground_lvl - BALL_DIAMETER)
{
velocity = velocity/4;
}
_ballY += velocity;
Thread.sleep(400);
this.repaint();//**problem occurs here**
}catch(InterruptedException ie)
{
}
}
}
public void mouseMoved (MouseEvent e){}
public void mouseEntered (MouseEvent e){}
public void mouseClicked (MouseEvent e){}
public void mouseReleased(MouseEvent e){}
}
main() class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class DragDemo extends JApplet
{
public static void main(String[] args) throws InterruptedException
{
JFrame window = new JFrame();
window.setTitle("Drag Demo");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//window.add(new DragBallPanel());
window.setContentPane(new DragBallPanel());
window.setResizable(false);
window.pack();
window.show();
}
public DragDemo() throws InterruptedException
{
new DragBallPanel();
}
}
This SSCCE begins to show the problems in the code.
Compile the code.
Run it.
Drag the ball upwards.
Release the ball.
Remove the mouse from the drawing area, to see..
The ball fall upwards!
You seem to have gotten the Y values upside down. They start at top of screen, and go downwards. Also, the code was blocking the EDT in an infinite loop. To solve that, run the animation using a Swing Timer.
Please read the document on the SSCCE & ask if there is anything in it you do not understand. I am well placed to explain. :)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DragBallPanel extends JPanel implements MouseListener, MouseMotionListener
{
private static final int BALL_DIAMETER = 40; // Diameter of ball
private int screen_size_x = 300;
private int screen_size_y = 300;
private int ground_lvl = screen_size_y - 15;
private int _ballX = ground_lvl/2;
private int _ballY = ground_lvl - BALL_DIAMETER;
private final double GRAVITY = -9.8;
private double velocity;
private static final double TERM_VEL = 100;
private int _dragFromX = 0; // pressed this far inside ball's
private int _dragFromY = 0; // bounding box.
/** true means mouse was pressed in ball and still in panel.*/
private boolean _canDrag = false;
public DragBallPanel()
{
setPreferredSize(new Dimension(screen_size_x, screen_size_y));
setBackground(Color.darkGray);
setForeground(Color.darkGray);
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g); // Required for background.
g.setColor (Color.green);
g.fillRect (0, 280, 400, 50 );
g.setColor (Color.black);
g.fillOval(_ballX, _ballY, BALL_DIAMETER, BALL_DIAMETER);
}
public void mousePressed(MouseEvent e)
{
int x = e.getX(); // Save the x coord of the click
int y = e.getY(); // Save the y coord of the click
if (x >= _ballX && x <= (_ballX + BALL_DIAMETER)
&& y >= _ballY && y <= (_ballY + BALL_DIAMETER)) {
_canDrag = true;
_dragFromX = x - _ballX; // how far from left
_dragFromY = y - _ballY; // how far from top
} else {
_canDrag = false;
}
}
//========= mouseDragged =================
/** Set x,y to mouse position and repaint. */
public void mouseDragged(MouseEvent e)
{
if (_canDrag) { // True only if button was pressed inside ball.
//--- Ball pos from mouse and original click displacement
_ballX = e.getX() - _dragFromX;
_ballY = e.getY() - _dragFromY;
//--- Don't move the ball off the screen sides
_ballX = Math.max(_ballX, 0);
_ballX = Math.min(_ballX, getWidth() - BALL_DIAMETER);
//--- Don't move the ball off top or bottom
_ballY = Math.max(_ballY, 0);
_ballY = Math.min(_ballY, getHeight() - BALL_DIAMETER);
this.repaint(); // Repaint because position changed.
}
}
//====================================================== method mouseExited
/** Turn off dragging if mouse exits panel. */
public void mouseExited(MouseEvent e)
{
System.out.println("Exited: " + e);
//_canDrag = false;
runGravity();
/* while(_ballY < ground_lvl)
{
simulateGravity();
}*/
}
Timer timer;
ActionListener animate;
public void runGravity() {
if (animate==null) {
animate = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("Ground: " + (_ballY-ground_lvl));
if (_ballY > ground_lvl) {
timer.stop();
} else {
simulateGravity();
}
}
};
timer = new Timer(100,animate);
}
timer.start();
}
public void simulateGravity()
{
System.out.println("_canDrag: " + _canDrag);
if(_canDrag)
{
velocity = velocity + GRAVITY;
if (velocity > TERM_VEL)
{
velocity = TERM_VEL;
}
if (_ballY >= ground_lvl - BALL_DIAMETER)
{
//We have hit the "ground", so bounce back up. Reverse
//the speed and divide by 4 to make it slower on bouncing.
//Just change 4 to 2 or something to make it faster.
velocity = velocity/4;
}
_ballY += velocity;
//this.revalidate();
this.repaint();
}
}
public void mouseMoved (MouseEvent e){}
public void mouseEntered (MouseEvent e){}
public void mouseClicked (MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
DragBallPanel dbp = new DragBallPanel();
JOptionPane.showMessageDialog(null, dbp);
}
});
}
}
Try updateUI() instead of repaint().
If there is no effect remove the component and add it again.