Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - onMousePressed() only detecting once

Tags:

java

swing

I have an array of JLabels[7] and I filled all JLabels with same image and added them to a JPanel.

When I click on a JLabel position(e.g I click on JLabel[5]) the console will print out "you have clicked JLabel 5" and change the JLabel image from imageOne to imageTwo.

I realized something about my codes which is after I clicked on a JLabel (e.g I click on JLabel[5]), the image changes from imageOne to imageTwo and the console print out "you have clicked JLabel 5" but if I clicked again and again on JLabel[5], the program will not detect my mouse click event and the console will not print out "you have clicked JLabel 5".

How do I make it such a way that after image has changed on the first click on a JLabel, it will still contiune and detect no mater how many times I clicked on the same JLabel again?.

 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);
   }
}
like image 249
user3820292 Avatar asked Feb 16 '26 10:02

user3820292


2 Answers

In your code you are removing the old JLabel when the listener invokes mouseClicked, and you are recreating it again with the new image. This causes the JLabel to lose the listener.

You could instead change the image of the label as follows:

@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()));
        }
    }
}
like image 189
M A Avatar answered Feb 18 '26 23:02

M A


No, you don't need to re-add any listeners. You need to not swap JLabels. Instead, keep your JLabels where they are and just swap ImageIcons. The key here is this: don't make things more difficult for yourself.


e.g.,

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();
         }
      });
   }
}
like image 33
Hovercraft Full Of Eels Avatar answered Feb 18 '26 22:02

Hovercraft Full Of Eels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!