有没有一种方法可以提取单击哪个JPanel?

时间:2019-05-02 16:54:38

标签: java swing mouseevent final

我正在尝试打印使用JPanel单击了JPanel数组中的哪个mouseEvent。我该怎么办?

它给我一个错误:

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中。

1 个答案:

答案 0 :(得分:0)

您可以从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);
      }
   }
}