开发者

Need Multiple JPanel's to respond its own mouse click events

I have multiple JPanels on my application, however I cannot figure out how to detect which exactly which one was clicked.

In my MouseListener, I have the argument e but my method isn't working

Early in my code I declare multiple JPanels and a listener object.


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 开发者_如何学PythonpnlClick = (JPanel)(e.getSource()); }*/ }//end calcListener


The problem would appear to be that you have a class variable and a local variable for each of your square panels.

Square square1 = new Square("1"); 

should be:

square1 = new Square("1"); 

now you will only have a class variable which the PuzzleListener can reference.


Is there a need to use a single MouseListener? You could create a new instance of your PuzzleListener and add it to each JPanel. That way there is no confusion as to which listener on which panel is getting fired.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜