0

First Time three random images shown on Jframe from three diffrent arrays. even MouseClicked Method triggered but images does not refresh in Frame. I want to refresh three random images each time i click on Frame. Please help

   import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;

import javax.swing.*;

public class Cards extends JFrame implements MouseListener {

    public static void main(String[] args) {
    JFrame frame = new Cards();     
        frame.setTitle("Cards");



        frame.setSize(500, 500);

        frame.setLocationRelativeTo(null);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);


        new Cards();

    }

    public Cards() {

        this.getContentPane().addMouseListener(this);

        cards1();
        cards2();
        cards3();

    }

    public void cards1() {

        ImageIcon[] images = new ImageIcon[10];
        for (int i = 1; i < images.length; i++) {

            images[i] = new ImageIcon("Drawables//Images//" + i + ".png");

        }

        int[] threeRandoms = new int[1];
        Random ran = new Random();

        for (int i = 0; i < threeRandoms.length; i++) {

            threeRandoms[i] = ran.nextInt(10);

        }

        setLayout(new GridLayout(1, 4, 5, 5));

        add(new JLabel(images[threeRandoms[0]]));

    }


    public void cards2() {

        ImageIcon[] images = new ImageIcon[10];
        for (int i = 1; i < images.length; i++) {

            images[i] = new ImageIcon("Drawables//Images1//" + i + ".png");

        }

        int[] threeRandoms = new int[1];
        Random ran = new Random();

        for (int i = 0; i < threeRandoms.length; i++) {

            threeRandoms[i] = ran.nextInt(10);

        }

        setLayout(new GridLayout(1, 4, 5, 5));

        add(new JLabel(images[threeRandoms[0]]));

    }

    public void cards3() {
        // this.getContentPane().addMouseListener(this);
        ImageIcon[] images = new ImageIcon[10];
        for (int i = 1; i < images.length; i++) {

            images[i] = new ImageIcon("Drawables//Images2//" + i + ".png");

        }

        int[] threeRandoms = new int[1];
        Random ran = new Random();

        for (int i = 0; i < threeRandoms.length; i++) {

            threeRandoms[i] = ran.nextInt(10);

        }

        // Labels with gridLayout

        setLayout(new GridLayout(1, 4, 5, 5));

        add(new JLabel(images[threeRandoms[0]]));

    }

    public void mouseClicked(MouseEvent e) {
        System.out.println("The frame was clicked.");
        new Cards();
    }

    public void mouseEntered(MouseEvent e) {
        System.out.println("The mouse entered the frame.");
    }

    public void mouseExited(MouseEvent e) {
        System.out.println("The mouse exited the frame.");

    }

    public void mousePressed(MouseEvent e) {
        System.out.println("The left mouse button was pressed.");

    }

    public void mouseReleased(MouseEvent e) {
        System.out.println("The left mouse button was released.");

    }

}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Usman Malik
  • 27
  • 1
  • 6

2 Answers2

1

I'm sorry, but I'm confused by your code. For one thing your cards1(), cards2() and cards3() methods look to be all the very same, and if so, why 3 different methods? Why not just one method? In those methods you appear to be trying to add JLabels repeatedly. Are you trying to add many many JLabels to the GUI? Or are you simply trying to display 3 images that change randomly on mouse action?

I would recommend structuring things a bit differently:

  • If possible, read all necessary images in once in your class's constructor, put the images into ImageIcons and then add them to an ArrayList or several ArrayLists if need be.
  • Don't add new JLabels each time a mouseClick occurs.
  • Create a JPanel give it a GridLayout and in your class constructor add to it three JLabels that are either instance fields or in an array or ArrayList.
  • Add this JPanel to your JFrame.
  • Add a MouseListener to each JLabel
  • in that MouseListener's mousePressed(MouseEvent e) method (not mouseClicked) randomize your number and use that number to call setIcon(...) on the JLabel source, obtained by calling getSource() on your MouseEvent parameter.

For example:

import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;

@SuppressWarnings("serial")
public class RandomImages extends JPanel {
   private static final int LABEL_COUNT = 3;
   private Random random = new Random();

   public RandomImages() {
      setLayout(new GridLayout(1, 3));
      for (int i = 0; i < LABEL_COUNT; i++) {
         final List<Icon> iconList = new ArrayList<>();

         // TODO: get images for the ith list 
         // and fill iconList with ImageIcons from the first grouping

         // create JLabel and give it the first Icon from the List above
         final JLabel label = new JLabel(iconList.get(0));
         label.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
               // get random number from random object using iconList.size()
               // get random Icon from list
               // set label's icon via setIcon(...)
            }
         });
         // add to GUI
         add(label);
      }
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("RandomImages");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new RandomImages());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

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

Concrete example 2:

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 java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class RandomChessMen extends JPanel {
   // for this example I get a sprite sheet that holds several sprite images in it
   // the images can be found here: http://stackoverflow.com/questions/19209650
   private static final String IMAGE_PATH = "https://i.stack.imgur.com/memI0.png";
   private static final int LABEL_COUNT = 2;
   private static final int ICON_COLUMNS = 6;
   private Random random = new Random();

   public RandomChessMen() throws IOException {
      URL url = new URL(IMAGE_PATH);
      BufferedImage largeImg = ImageIO.read(url);
      setLayout(new GridLayout(1, 0));

      // break down large image into its constituent sprites and place into ArrayList<Icon>
      int w = largeImg.getWidth() / ICON_COLUMNS;
      int h = largeImg.getHeight() / LABEL_COUNT;
      for (int i = 0; i < LABEL_COUNT; i++) {
         final List<Icon> iconList = new ArrayList<>();
         int y = (i * largeImg.getHeight()) / LABEL_COUNT;
         // get 6 icons out of large image
         for (int j = 0; j < ICON_COLUMNS; j++) {
            int x = (j * largeImg.getWidth()) / ICON_COLUMNS;
            // get subImage
            BufferedImage subImg = largeImg.getSubimage(x, y, w, h);
            // create ImageIcon and add to list
            iconList.add(new ImageIcon(subImg));
         }

         // create JLabel
         final JLabel label = new JLabel("", SwingConstants.CENTER);
         int eb = 40;
         label.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));

         // get random index for iconList
         int randomIndex = random.nextInt(iconList.size());
         Icon icon = iconList.get(randomIndex); // use index to get random Icon
         label.setIcon(icon); // set label's icon
         label.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
               Icon secondIcon = label.getIcon();
               // so we don't repeat icons
               while (label.getIcon() == secondIcon) {
                  int randomIndex = random.nextInt(iconList.size());
                  secondIcon = iconList.get(randomIndex);
               }
               label.setIcon(secondIcon);
            }
         });
         // add to GUI
         add(label);
      }
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("RandomImages");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      try {
         frame.getContentPane().add(new RandomChessMen());
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

I have made these changes to your code:

  • Instead of having three methods cards1() cards2() cards3(), i have just made one cards() method.
  • Everytime you click on the frame, three random images get loaded.
  • I have set every image inside a JLabel in order to make it easy to update it.

The code below works perfectly according to your needs.

package example;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;


public class Cards extends JFrame implements MouseListener {

    JPanel subPanel1;
    JLabel label1, label2, label3;

    static ImageIcon[] images ;
    static Random ran ;
    static int[] threeRandoms;


    public Cards() {

        super("Cards");

        subPanel1 = new JPanel();

        // Set up first subpanel        
        subPanel1.setPreferredSize (new Dimension(400, 400));
        //subPanel1.setBackground (Color.cyan);
        label1 = new JLabel ("image 1",SwingConstants.CENTER);
        label2 = new JLabel ("image 2", SwingConstants.LEFT);
        label3 = new JLabel ("image 3",  SwingConstants.CENTER);

        subPanel1.add (label1);
        subPanel1.add (label2);
        subPanel1.add (label3);

        add(subPanel1);

        addMouseListener(this);
        setSize(500, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        System.out.println("Success.....");
    }

    public void cards() {


        for (int i = 0; i < threeRandoms.length; i++)
            threeRandoms[i] = ran.nextInt(3);


            label1.setIcon(images[threeRandoms[0]]);
            label2.setIcon(images[threeRandoms[1]]);
            label3.setIcon(images[threeRandoms[2]]);


    }

    @Override
    public void mouseClicked(MouseEvent e) {
        System.out.println("mouseClicked");
        cards();
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        System.out.println("mouseEntered");
    }

    @Override
    public void mouseExited(MouseEvent e) {
        System.out.println("mouseExited");
    }

    @Override
    public void mousePressed(MouseEvent e) {
        System.out.println("mousePressed");
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        System.out.println("mouseReleased");
    }

    public static void loadImages(){
        images = new ImageIcon[4];
        ran = new Random();
        threeRandoms = new int[3];
        for (int i = 1; i <= images.length; i++) {

            images[i-1] = new ImageIcon("Drawables//Images//" + i + ".png");

        }
    }

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

}
MChaker
  • 2,610
  • 2
  • 22
  • 38
  • It shows first tow images of cards1() and cards() It did not genrates a random images – Usman Malik Apr 30 '15 at 19:08
  • You're suggesting that he keep re-adding a new JList over and over again? Why? – Hovercraft Full Of Eels Apr 30 '15 at 19:09
  • @UsmanMalik Answer edited. I hope it works but please make sure of images path ;) – MChaker Apr 30 '15 at 20:04
  • @HovercraftFullOfEels How about now (answer edited)? – MChaker Apr 30 '15 at 20:04
  • Some problems that I see with your code: 1) You're calling `frame.setVisible(true);` **before** you've added all components to the JFrame. 2) You're setting sizes and not packing your JFrame. 3) You're re-reading in the images with each mouse click rather than reading them in once and storing them to a collection or collections. 4) You're unnecessarily creating a new Random object with each call to `cards()` rather than creating one Random object once. 5) You're not starting your GUI on the Swing event thread. 5) You're using SwingConstants incorrectly. – Hovercraft Full Of Eels Apr 30 '15 at 21:27
  • Please note that I'm not trying to be harsh on you, but you did in fact ask me to critique your code, and so that is what I've given you. – Hovercraft Full Of Eels Apr 30 '15 at 21:31
  • @HovercraftFullOfEels Sir I really appreciate your help to review my code. I am sorry for wasting your time. But Can you explain to me the last two problems `5) 6)`? – MChaker Apr 30 '15 at 21:49
  • Swing uses a single thread, the Event Dispatch Thread or **EDT** to do all graphics and user interactions, and so Swing GUI's should be started on this thread, for instance as I do in my main method -- by creating a Runnable and queuing it onto the EDT via `SwingUtilities.invokeLater(...)`. Regarding SwingConstants, I withdraw my criticism, although I'm not sure why you're using them. – Hovercraft Full Of Eels Apr 30 '15 at 21:53