我正在使用 MouseListener,特别是 MouseClick 和一个图像。图像在面板周围移动。
如何使当我在其当前位置的 30 像素范围内单击时,图像会交替显示?
这是我的框架。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
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);
}
}
这是我的小组。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
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;
private ImageIcon image2;
public ReboundPanel()
{
timer = new Timer(DELAY, new ReboundListener());
image = new ImageIcon("C:\\happyFace.gif");
image2 = new ImageIcon("C:\\red smiley.gif");
x = 0;
y = 40;
moveX = moveY = 3;
setPreferredSize (new Dimension(WIDTH, HEIGHT));
setBackground (Color.black);
addMouseListener(new MousePressListener());
timer.start();
}
public void paintComponent (Graphics page)
{
super.paintComponent (page);
image.paintIcon (this, page, x, y);
}
class MousePressListener implements MouseListener
{
public void mousePressed(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}
public void mouseClicked(MouseEvent event) {
image = image2;
}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
}
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();
}
}
}