-
May 4th, 2013, 07:59 PM
#1
start, stop timer in jpanel, please help
I tried to add a timer with a start stop when mouse is clicked, but it is not working at all. Could someone please help me. it is the If statements for the timer. any help is much appreciate. thank you
Code:
//**********************************************************************
// ReboundPanel.java Java Foundations
//
// Represents the primary panel for the rebound program.
//**********************************************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//import PP6_10Panel.Handlerclass;
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;
boolean b;
//-------------------------------------------------------------------
// Sets up the panel, including the timer for the animation
//-------------------------------------------------------------------
public ReboundPanel()
{
timer = new Timer(DELAY, new ReboundListener(){
@Override
public void actionPerformed(ActionEvent ae) {
// change polygon data
// ...
repaint();
}
});
image = new ImageIcon ("C:/Users/dstevens/Desktop/happyFace.gif");//.getImage();
x = 0;
y = 40;
moveX = moveY = 3;
setPreferredSize (new Dimension(WIDTH, HEIGHT));
setBackground (Color.black);
timer.start();
//Handlerclass handler = new Handlerclass();
}
//--------------------------------------------------------------------
// Draw the image in the current location
//--------------------------------------------------------------------
@Override
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 the possibly the direction
//of the movement whenever the timer fires an action event.
//******************************************************************
public void actionPerformed (ActionEvent event)
{
x += moveX;
y += moveY;
if (b) {
//timer.start();
if (x <= 0 || x >= WIDTH-IMAGE_SIZE)
moveX = moveX * -1;
if (y <= 0 || y >= HEIGHT-IMAGE_SIZE)
moveY = moveY * -1;
repaint();
} else {
timer.stop();
}
b = !b;
}
}
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|