我的應用程序有多個JPanel,但我無法弄清楚如何檢測到哪一個被點擊。需要多個JPanel來響應它自己的鼠標點擊事件
在我的MouseListener,我的說法,但ê我的方法是行不通的
早在我的代碼聲明多個JPanels和偵聽器對象。
PuzzleListener plist = new PuzzleListener();
JPanel puzzle_board = new JPanel(new GridLayout(4,4,5,5));
...
Square square1 = new Square("1");
Square square2 = new Square("2");
...
puzzle_board.add(square1);
puzzle_board.add(square2);
...
square1.addMouseListener(plist);
square1.addMouseListener(plist);
class PuzzleListener implements MouseListener {
public void mouseClicked(MouseEvent e)
{
JPanel pnlClick = (JPanel)(e.getSource());
//System.out.println(pnlClick);
//System.out.println(e.getSource());
//System.out.println(e.getComponent().getClass());
//System.out.println(e.getComponent().getClass().getName());
//problem is here
if(pnlClick == square1)
{
System.out.println("Panel 1 has been clicked");
}
if(pnlClick == square2)
{
System.out.println("Panel 2 has been clicked");
}
}
public void mouseExited(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
//System.out.println("Panel 1 has been clicked");
}
public void mouseReleased(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
/*
public void actionPerformed(ActionEvent e)
{
JPanel pnlClick = (JPanel)(e.getSource());
}*/
}//end calcListener
我完全忘了接受我以前的答案=)感謝提醒。 – 2010-09-20 21:46:27