如何从mouseEntered方法内的“for”循环中返回变量?

时间:2014-03-19 18:27:22

标签: java swing mouseevent

我创建了一个stadiumPanel类,它包含一个JButtons的二维数组,每个都有自己的MouseListener。每个按钮对应一个“Seat”对象,它包含一组数据(在一个单独的数据类中),当我用鼠标悬停在按钮上时,我想抓取与该按钮对应的数据并将其显示在我的父类(JWindow)。

为此,我试图在MouseEntered()方法中使用两个嵌套的“for”循环,然后使用MouseEvent.getSource()来搜索悬停的JButton(以及因此对应的正确的座位)。然后使用我的“stad.getSeat”方法返回给定索引处的Seat对象。然后,从for循环中,我想将该座位存储在我的“seatHovered”变量中,以便我可以从另一个类访问与该Seat相对应的数据。但是,我无法在“for”循环中更改hoveredSeat变量。

我该怎么做?

public class StadiumPanel extends JPanel implements MouseListener
{

Seat hoveredSeat;
Stadium stad;
JButton[][] buttons = new JButton[Stadium.ROWS+1][Stadium.COLUMNS+1];


public StadiumPanel(Stadium s){

stad = s;

for (int row = 0; row < Stadium.ROWS; row++){
  for (int col = 0; col < Stadium.COLUMNS; col++){
      buttons[row][col] = new JButton();
      add(buttons[row][col]);
      buttons[row][col].addMouseListener(this);
    }
  }
}


public void mouseEntered(MouseEvent e)
{
  for (int row = 0; row < Stadium.ROWS; row++){
    for (int col = 0; col < Stadium.COLUMNS; col++){
      if (e.getSource() == buttons[row][col] && buttons[row][col] != null){ 
           hoveredSeat = stad.getSeat(row,col);
        }
      }
    }
  }
}

如果这个问题荒谬可笑,我道歉。任何意见都非常感谢。

0 个答案:

没有答案
相关问题