【问题标题】:Is there a way to extract which JPanel is clicked?有没有办法提取点击了哪个JPanel?
【发布时间】:2019-09-21 05:53:25
【问题描述】:

我正在尝试使用mouseEvent 打印已单击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中。

【问题讨论】:

标签: java swing mouseevent final


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-09-08
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    相关资源
    最近更新 更多