我有一个地图作为背景(一个JLabel),我添加了多个Jlabels(作为棋子)。我有一个地图的mouselistener,以便它将我的棋子移动到所需的位置。但它只适用于最后添加的pawn.why是什么?我如何让它循环遍历我的所有jlabels?我正在使用MVC模式。
我需要将mouseListener分配给地图,以便为所有JLabel提供移动区域。
来自Controller的代码:
this.view.addIconListener(new DragMouseAdapter());
class DragMouseAdapter extends MouseAdapter {
private Point initialLoc;
private Point initialLocOnScreen;
public void mousePressed(MouseEvent e) {
JComponent comp = (JComponent)e.getSource();
initialLoc = comp.getLocation();
initialLocOnScreen = e.getLocationOnScreen();
}
public void mouseReleased(MouseEvent e) {
/*saySomething("Mouse released; # of clicks: "
+ e.getClickCount(), e);*/
}
public void mouseEntered(MouseEvent e) {
//saySomething("Mouse entered", e);
}
public void mouseExited(MouseEvent e) {
//saySomething("Mouse exited", e);
}
public void mouseClicked(MouseEvent e) {
for(int i = 0; i < 199; i++)
{
if((xAxis.get(i) - 15 < e.getX() && xAxis.get(i) + 15 > e.getX()) &&
(yAxis.get(i)- 10< e.getY() && yAxis.get(i) +10 > e.getY() ))
{
System.out.println("tada" + (i + 1));
//System.out.println(x + " " + y);
view.setCurrentPlayer(model.getCurrentPlayer());
view.validate();
//view.addIconListener(this);
System.out.println(model.getCurrentPlayer());
view.setPlayerLocation(xAxis.get(i), yAxis.get(i));
break;
}
}
}
来自GUI的代码:
JLabel yellowPlayer = new JLabel(new ImageIcon("solution/yellow5.png"));
JLabel blackPlayer = new JLabel(new ImageIcon("solution/black5.png"));
JLabel bluePlayer = new JLabel(new ImageIcon("solution/blue5.png"));
JLabel redPlayer = new JLabel(new ImageIcon("solution/red5.png"));
JLabel whitePlayer = new JLabel(new ImageIcon("solution/white5.png"));
JLabel greenPlayer = new JLabel(new ImageIcon("solution/green5.png"));
JLabel map = new JLabel(new ImageIcon("solution/map2.jpg"));
public void addIconListener(MouseListener dragger)
{
map.addMouseListener(dragger);
}
public void createPanel2()
{ /*middle part of a splitPanel(using 2 JSplitPane) splitted in three*/
panel2 = new JPanel() ;
panel2.add(map);
}
public void setPlayerLocation(int x, int y)
{
if(selectedColour.equals(Colour.Black))
{
map.add(blackPlayer);
blackPlayer.setBounds(x - 13, y - 13, 28, 28);
blackPlayer.setVisible(true);
}
if(selectedColour.equals(Colour.Blue))
{
map.add(bluePlayer);
bluePlayer.setBounds(x - 13, y - 13, 28, 28);
bluePlayer.setVisible(true);
}
if(selectedColour.equals(Colour.White))
{
whitePlayer.setBounds(x - 13, y - 13, 28, 28);
whitePlayer.setVisible(true);
map.add(whitePlayer);
}
if(selectedColour.equals(Colour.Green))
{
greenPlayer.setBounds(x - 13, y - 13, 28, 28);
greenPlayer.setVisible(true);
map.add(greenPlayer);
}
if(selectedColour.equals(Colour.Yellow))
{
yellowPlayer.setBounds(x - 13, y - 13, 28, 28);
yellowPlayer.setVisible(true);
map.add(yellowPlayer);
}
if(selectedColour.equals(Colour.Red))
{
redPlayer.setBounds(x - 13, y - 13, 28, 28);
redPlayer.setVisible(true);
map.add(redPlayer);
}
}