我有4个瓷砖:蓝色,红色,绿色和黄色。当鼠标在瓷砖上移动时,我希望它点亮(只需将图像更改为浅色图像)。相反,没有任何事情发生。
我做了一些简单的调试,并且知道图像被正确导入并且mouseOverTile [0]变为true。
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Arrays;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
public class MainGame extends JApplet implements MouseListener, Runnable
{
private static final long serialVersionUID = 1L;
Thread animator = null;
Image blue, blueLit, red, redLit, green, greenLit, yellow, yellowLit;
boolean takingTurn;
boolean[] mouseOverTile = new boolean[4];
public void init()
{
setSize(500, 500);
blue = new ImageIcon("Images/Blue.png").getImage();
blueLit = new ImageIcon("Images/Blue_Lit.png").getImage();
red = new ImageIcon("Images/Red.png").getImage();
redLit = new ImageIcon("Images/Red_Lit.png").getImage();
green = new ImageIcon("Images/Green.png").getImage();
greenLit = new ImageIcon("Images/Green_Lit.png").getImage();
yellow = new ImageIcon("Images/Yellow.png").getImage();
yellowLit = new ImageIcon("Images/Yellow_Lit.png").getImage();
Arrays.fill(mouseOverTile, false);
takingTurn = true;
addMouseListener(this);
}
public void start()
{
if(animator == null)
{
animator = new Thread(this);
}
}
public void stop()
{
animator = null;
}
@Override
public void run()
{
while(Thread.currentThread() == animator)
{
try
{
Thread.sleep(1);
repaint();
}
catch(Exception e)
{ }
}
}
public void paint(Graphics g)
{
if(!mouseOverTile[0])
{
g.drawImage(blue, 50, 50, this);
} else g.drawImage(blueLit, 50, 50, this);
if(!mouseOverTile[1])
{
g.drawImage(red, 260, 50, this);
} else g.drawImage(redLit, 260, 50, this);
if(!mouseOverTile[2])
{
g.drawImage(green, 50, 260, this);
} else g.drawImage(greenLit, 50, 260, this);
if(!mouseOverTile[3])
{
g.drawImage(yellow, 260, 260, this);
} else g.drawImage(yellowLit, 260, 260, this);
}
@Override
public void mouseClicked(MouseEvent e)
{
System.out.println("Mouse X: " + e.getX());
System.out.println("Mouse Y: " + e.getY());
}
@Override
public void mouseEntered(MouseEvent e)
{
if(takingTurn)
{
if(e.getX() > 50 && e.getX() < 250)
{
mouseOverTile[0] = true;
System.out.println(mouseOverTile[0]);
}
}
}
@Override
public void mouseExited(MouseEvent e)
{
if(takingTurn)
{
if(e.getX() < 50 || e.getX() > 250)
{
mouseOverTile[0] = false;
System.out.println(mouseOverTile[0]);
}
}
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:3)
您尚未更新视图。
进行一些更改后,请致电repaint()
。
例如,在mouseEntered(...)
内的代码中:
@Override
public void mouseEntered(MouseEvent e)
{
if(takingTurn)
{
if(e.getX() > 50 && e.getX() < 250)
{
mouseOverTile[0] = true;
System.out.println(mouseOverTile[0]);
repaint();
}
}
}