我的应用程序上有多个JPanels,但是我无法弄清楚如何准确地检测到哪个被单击。

在我的MouseListener中,我有参数e,但是我的方法不起作用

在我的代码的早期,我声明了多个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

最佳答案

问题似乎是您在每个方形面板上都有一个类变量和一个局部变量。

Square square1 = new Square("1");


应该:

square1 = new Square("1");


现在,您将只有一个可供PuzzleListener引用的类变量。

关于java - 需要多个JPanel来响应自己的鼠标单击事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3755363/

10-09 12:52