Image did not fresh in Frame on Mouse Click In Java

狂风中的少年 提交于 2019-12-10 12:19:02

问题


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.");

    }

}

回答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 = "http://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();
         }
      });
   }
}



回答2:


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();
             }
          });       
    }

}


来源:https://stackoverflow.com/questions/29975472/image-did-not-fresh-in-frame-on-mouse-click-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!