java - onMousePressed()只检测一次

时间:2014-07-12 15:28:51

标签: java swing

我有一个JLabels数组[7],我用相同的图像填充所有JLabel并将它们添加到JPanel。

当我点击JLabel位置时(例如我点击JLabel [5]),控制台将打印出来#34;您已点击JLabel 5"并将JLabel图像从imageOne更改为imageTwo。

我意识到我的代码是在我点击JLabel之后(例如我点击JLabel [5]),图像从imageOne变为imageTwo,控制台打印出来"你点击了JLabel 5&# 34;但是如果我在JLabel [5]上一次又一次地点击,程序将无法检测到我的鼠标点击事件,并且控制台将不会打印出来#34;您已经点击了JLabel 5"。

如何使它在第一次点击JLabel后图像发生变化之后,它仍然会继续进行检测并且无法检测到我再次点击同一个JLabel多少次?

 import java.awt.FlowLayout;
 import java.awt.Image;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
 import java.awt.image.BufferedImage;
 import java.io.File;
 import javax.imageio.ImageIO;
 import javax.swing.ImageIcon;
 import javax.swing.JFrame;
 import javax.swing.JLabel;
 import javax.swing.JPanel;

 public class LearningSwing {

     public Image imageOne() {
         BufferedImage img = null;
         try {
             img = ImageIO.read(new File("imageOne.jpg"));   
         } catch (Exception e) {
           }
         return img;
    }

    public Image imageTwo() {
        BufferedImage img = null;
        try {
            img = ImageIO.read(new File("imageTwo.jpg"));    
        } catch (Exception e) {
          }
        return img;
    }

    public static void main(String[] args) {
        final JLabel[] jLabelArr = new JLabel[7];
        final JPanel jPanel = new JPanel(new FlowLayout());
        JFrame frame = new JFrame();
        final LearningSwing learningSwing = new LearningSwing();
        for(int i = 0; i< 7; i++) {
            jLabelArr[i] = new JLabel(new ImageIcon(learningSwing.imageOne()));
            jPanel.add(jLabelArr[i]);
            jLabelArr[i].addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    for(int i = 0; i < 7; i ++) {
                        if(e.getSource() == jLabelArr[i]) { 
                            System.out.println("You clicked on JLabel" + i);
                            jPanel.remove(i);
                            jLabelArr[i] = new JLabel(new ImageIcon(learningSwing.imageTwo()));
                            jPanel.add(jLabelArr[i],i);
                            jPanel.revalidate();
                            jPanel.repaint();   
                        }
                    }
                }
            });     
        }
        frame.add(jPanel);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setSize(400,600);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
   }
}

2 个答案:

答案 0 :(得分:2)

在您的代码中,当侦听器调用JLabel时,您将删除旧的mouseClicked,并使用新映像重新创建它。这会导致JLabel失去监听器。

您可以改为更改标签的图像,如下所示:

@Override
public void mouseClicked(MouseEvent e) {
    for (int i = 0; i < 7; i++) {
        if (e.getSource() == jLabelArr[i]) {
            System.out.println("You clicked on JLabel" + i);
            jLabelArr[i].setIcon(new ImageIcon(learningSwing.imageTwo()));
        }
    }
}

答案 1 :(得分:2)

不,您不需要重新添加任何听众。你不需要交换JLabel。相反,将JLabel保持原样,只需交换ImageIcons即可。关键在于:不要让事情变得更加困难。


如,

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class LearningSwing2 extends JPanel {
   private static final String[] IMAGE_PATHS = {"imageOne.jpg", "imageTwo.jpg"};
   private static final int LABEL_COUNT = 7;
   private List<Icon> icons = new ArrayList<>();
   private JLabel[] imageLabels = new JLabel[LABEL_COUNT];


   public LearningSwing2() throws IOException {
      for (String imagePath : IMAGE_PATHS) {
         BufferedImage img = ImageIO.read(new File(imagePath));
         icons.add(new ImageIcon(img));
      }

      for (int i = 0; i < imageLabels.length; i++) {
         imageLabels[i] = new JLabel(icons.get(0));
         imageLabels[i].addMouseListener(new LabelListener());
      }
   }

   private class LabelListener extends MouseAdapter {
      @Override
      public void mousePressed(MouseEvent mEvt) {
         JLabel label = (JLabel) mEvt.getSource();
         for (int i = 0; i < imageLabels.length; i++) {
            if (label == imageLabels[i]) {
               System.out.println("You pressed image label " + i);
            }
         }
         label.setIcon(icons.get(1));
      }
   }

   private static void createAndShowGui() {
      LearningSwing2 mainPanel;
      try {
         mainPanel = new LearningSwing2();
         JFrame frame = new JFrame("LearningSwing2");
         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         frame.getContentPane().add(mainPanel);
         frame.pack();
         frame.setLocationByPlatform(true);
         frame.setVisible(true);
      } catch (IOException e) {
         e.printStackTrace();
      }

   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}