有没有办法提取点击了哪个 JPanel?

Is there a way to extract which JPanel is clicked?

我正在尝试打印使用 [​​=14=] 单击了 JPanel 数组中的哪个 JPanel。我该怎么做?

它给我一个错误:

Local variable i defined in an enclosing scope must be final or effectively final

for(int i=0; i<count[0]; i++) {
    p1[i] = new JPanel();
    l1[lcount] = new JLabel("Panel "+(i+1));
    p1[i].add(l1[lcount]);
    panel_2.add(p1[i]);
    lcount++;
    p1[i].addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println(i);
        }
    });
}

我想提取i的值并显示在另一个JLabel中。

您可以使用 mouseEvent() 中的 e.getSource()。只需将其投射到 JPanel。

这是一个例子。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseEventSource {
   JFrame frame = new JFrame();

   public static void main(String[] args) {
      new MouseEventSource().start();
   }

   public void start() {
      JPanel p1 = createPanel("Panel 1", Color.BLUE);
      JPanel p2 = createPanel("Panel 2", Color.RED);
      MyMouseListener ml = new MyMouseListener();
      p1.addMouseListener(ml);
      p2.addMouseListener(ml);
      frame.setLayout(new FlowLayout());
      frame.add(p1);
      frame.add(p2);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }

   public JPanel createPanel(String name, Color color) {
      JPanel panel = new JPanel() {
         public String toString() {
            return name;
         }
      };
      panel.setBackground(color);
      panel.setPreferredSize(new Dimension(250, 250));
      return panel;
   }

   private class MyMouseListener extends MouseAdapter {
      public void mouseClicked(MouseEvent e) {
         // not really necessary to print toString()
         JPanel panel = (JPanel) e.getSource();
         System.out.println(panel);
      }
   }
}