-2

Here is my code. I want to know which l was clicked and then in a new frame, display that ImageIcon.

The e.getSource() is not working...

final JFrame shirts = new JFrame("T-shirts");
JPanel panel = new JPanel(new GridLayout(4, 4, 3, 3));

for (int i = 1; i < 13; i++) {
    l = new JLabel(new ImageIcon("T-shirts/"+i+".jpg"), JLabel.CENTER);
    l.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
    l.setFont(l.getFont().deriveFont(20f));
    panel.add(l);
}//end of for loop

panel.addMouseListener(new MouseAdapter(){  
    public void mouseClicked(MouseEvent e)  
    {
        sizes = new JFrame("Shopping");
        sizes.setVisible(true);
        sizes.setSize(500, 500);
        sizes.setLocation(100,200);
        shirts.dispose();
        if(e.getSource()==l){//FIX
            sizes.add(l);
        }//end of if
    }  
});

shirts.setContentPane(panel);
shirts.setSize(1000, 1000);
shirts.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
shirts.setVisible(true);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
jjj
  • 27
  • 8
  • For a better user experience change 1) The label for a button (possibly undecorated). 2) The mouse listener for an action listener (responds to both mouse and keyboard). 3) The frame for a dialog or option pane. See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) – Andrew Thompson Apr 19 '15 at 20:29

2 Answers2

3

If you add your MouseListener directly to your JLabels, then you can display the pressed label's icon easily in a JOptionPane:

@Override
public void mousePressed(MouseEvent mEvt) {
   JLabel label = (JLabel) mEvt.getSource();
   Icon icon = label.getIcon();
   JOptionPane.showMessageDialog(label, icon);
}

For example:

import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

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

public class FooMouseListener extends JPanel {
   private GetImages getImages;

   public FooMouseListener() throws IOException {
      getImages = new GetImages();
      setLayout(new GridLayout(GetImages.SPRITE_ROWS, GetImages.SPRITE_COLS));
      MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
      for (int i = 0; i < GetImages.SPRITE_CELLS; i++) {
         JLabel label = new JLabel(getImages.getIcon(i));
         add(label);
         label.addMouseListener(myMouseAdapter);
      }
   }

   private class MyMouseAdapter extends MouseAdapter {
      @Override
      public void mousePressed(MouseEvent e) {
         JLabel label = (JLabel) e.getSource();
         Icon icon = label.getIcon();
         JOptionPane.showMessageDialog(label, icon, "Selected Icon", JOptionPane.PLAIN_MESSAGE);
      }
   }

   private static void createAndShowGui() {
      FooMouseListener mainPanel = null;
      try {
         mainPanel = new FooMouseListener();
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }

      JFrame frame = new JFrame("FooMouseListener");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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

class GetImages {
   private static final String SPRITE_PATH = "http://th02.deviantart.net/"
         + "fs70/PRE/i/2011/169/0/8/blue_player_sprite_sheet_by_resetado-d3j7zba.png";
   public static final int SPRITE_ROWS = 6;
   public static final int SPRITE_COLS = 6;
   public static final int SPRITE_CELLS = SPRITE_COLS * SPRITE_ROWS;

   private List<Icon> iconList = new ArrayList<>();

   public GetImages() throws IOException {
      URL imgUrl = new URL(SPRITE_PATH);
      BufferedImage mainImage = ImageIO.read(imgUrl);

      for (int i = 0; i < SPRITE_CELLS; i++) {
         int row = i / SPRITE_COLS;
         int col = i % SPRITE_COLS;
         int x = (int) (((double) mainImage.getWidth() * col) / SPRITE_COLS);
         int y = (int) ((double) (mainImage.getHeight() * row) / SPRITE_ROWS);
         int w = (int) ((double) mainImage.getWidth() / SPRITE_COLS);
         int h = (int) ((double) mainImage.getHeight() / SPRITE_ROWS);
         BufferedImage img = mainImage.getSubimage(x, y, w, h);
         ImageIcon icon = new ImageIcon(img);
         iconList.add(icon);
      }
   }

   // get the Icon from the List at index position
   public Icon getIcon(int index) {
      if (index < 0 || index >= iconList.size()) {
         throw new ArrayIndexOutOfBoundsException(index);
      }

      return iconList.get(index);
   }

   public int getIconListSize() {
      return iconList.size();
   }

}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

Have you tried this?

public void mouseClicked(MouseEvent e)  
{

       sizes = new JFrame("Shopping");
       sizes.add(l);
       sizes.setVisible(true);
       sizes.setSize(500, 500);
       sizes.setLocation(100,200);
       shirts.dispose();

//Remove the "e.getSource()" part.


}  

It will automatically display the image, because you are assigning the Image Name to it, in the same segment as the Addition to the new JFrame.

Let me know of the outcome

TejjD
  • 2,571
  • 1
  • 17
  • 37
  • Yes that only shows the last image added to the JLabel and not the image clicked. – jjj Apr 19 '15 at 21:41
  • Ok then the alternative is to set the Name of each JLabel to the path of your image. There after each time you display it you get the name ("l.get text()") ... It will work – TejjD Apr 19 '15 at 21:44
  • How would I go about accomplishing that? – jjj Apr 19 '15 at 21:48
  • Ok when creating the Label in your for loop instead of saying "new ImageIcon" .. Just put "T-shirts/" + i + ".jpg" ... Then you create another JLabel on the mouselistener that will get the Text of the previous label and use it as the path for the ImageIcon and add this new label to the next frame – TejjD Apr 19 '15 at 21:53
  • Oh right you want to display the labels as images then use the same image on the next Frame. Okay in that case change what you are doing. But create the array of labels we discussed before. Create 2 JLabels, one will display immediately with your image and the other will contain the text of your path and be stored in the array. Then create your mouse listener apart from your code. Add a mouse listener to the labels using (this). Then in your method for mouse listener you have a if statements that will check the source that was clicked i.e if(e.getSource() == arrayName(0)). – TejjD Apr 19 '15 at 21:59
  • So you will have if statements to check if the source is any of the 13 Labels within the array. Then based on that you simply use the code to create a new Frame and add the label with the image icon using the path stored on the label as getText() – TejjD Apr 19 '15 at 22:01
  • How do I get the text of the path? – jjj Apr 19 '15 at 22:03
  • The second label you are creating will be new JLabel("part of image") ... Then this label will go into your array. In your mouse listener you will say, for example, if(e.getSource() == array.get(1)){ OtherFrame f = new OtherFrame; JLabel newL = new JLabel(new ImageIcon(array.get(1).get text()); f.add(newL); f.setVisible(true); and so on. Does that make sense now? – TejjD Apr 19 '15 at 22:07
  • Sorry I'm assisting you from my phone, so it is difficult to format the code appropriately. – TejjD Apr 19 '15 at 22:08
  • What type of array should it be? The getText() isn't working for some odd reason... – jjj Apr 20 '15 at 10:13
  • It should be an ArrayList of type JLabel – TejjD Apr 20 '15 at 10:49
  • Why does the .getText() method not work? Do I have to import something? Here is my code: – jjj Apr 20 '15 at 21:04
  • panel.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e) { sizes = new JFrame("Shopping"); sizes.setVisible(true); sizes.setSize(500, 500); sizes.setLocation(100,200); shirts.dispose(); for(int i=1; i<13; i++){ if(e.getSource()==select.get(i)){//Fix this line!! JLabel pls = new JLabel(new ImageIcon(select.get(i).getText())); sizes.add(pls); }//end of if }//end of for – jjj Apr 21 '15 at 02:17