This is my first time trying to use mouselistener, unfortunately is not going well
/>. Everytime i click 15 units from the moving image it should change the current image to a new one and if i click again it would change it back, so the images would be alternating. I was able to ge the image to move but i'm so lost about changing them with mouselistener. My book does a poor job on this topic. BTW i have the main in another class, one that calls the contents of the moving class.
Any help would be appreciated.
Any help would be appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Moving extends JPanel implements MouseListener
{
private final int WIDTH = 300, HEIGHT = 100;
private final int DELAY = 20, IMAGE_SIZE = 35;
private ImageIcon image;
private ImageIcon image2;
private Timer timer;
private int x, y, moveX, moveY;
public Moving()
{
timer = new Timer(DELAY, new Moving());
image = new ImageIcon ("oldface.gif");
x = 0;
y = 40;
moveX = moveY = 3;
setPreferredSize (new Dimension(WIDTH, HEIGHT));
setBackground (Color.black);
timer.start();
addMouseListener(this);
}
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 >= WIDTH-IMAGE_SIZE)
moveX = moveX * -1;
if (y <= 0 || y >= HEIGHT-IMAGE_SIZE)
moveY = moveY * -1;
repaint();
}
}
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if(e.getX()==x+15)
image2 = new ImageIcon ("newface.gif");
repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}