私は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();
}
}
}