图像在鼠标点击帧时不新鲜 Java

Image did not fresh in Frame on Mouse Click In Java

第一次在 Jframe 上显示来自三个不同阵列的三个随机图像。 即使触发了 MouseClicked 方法,但图像不会在框架中刷新。 每次单击框架时,我都想刷新三个随机图像。 请帮助

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

    }

}

抱歉,我对您的代码感到困惑。一方面,您的 cards1()cards2()cards3() 方法看起来完全相同,如果是这样,为什么有 3 种不同的方法?为什么不只是一种方法?在这些方法中,您似乎在尝试重复添加 JLabel。您是否正在尝试向 GUI 添加许多 JLabel?或者您只是想显示 3 张随鼠标操作随机变化的图像?

我建议以不同的方式构建事物:

  • 如果可能,请在 class 的构造函数中一次读取所有必要的图像,将图像放入 ImageIcons,然后将它们添加到一个 ArrayList 或多个 ArrayList(如果需要)。
  • 不要在每次鼠标点击时添加新的 JLabel。
  • 创建一个 JPanel 并为其提供一个 GridLayout,然后在您的 class 构造函数中向其添加三个 JLabel,这些 JLabel 可以是实例字段,也可以是数组或 ArrayList 中的。
  • 将此 JPanel 添加到您的 JFrame。
  • 为每个 JLabel 添加一个 MouseListener
  • 在 MouseListener 的 mousePressed(MouseEvent e) 方法(不是 mouseClicked)中随机化您的号码并使用该号码调用 JLabel 源上的 setIcon(...),通过调用 getSource() 获得你的 MouseEvent 参数。

例如:

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

具体例子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: 
   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();
         }
      });
   }
}

我已经对您的代码进行了这些更改:

  • 我没有使用三种方法 cards1() cards2() cards3(),而是使用了一种 cards() 方法。
  • 每次单击框架时,都会加载三张随机图像。
  • 为了方便更新,我把每张图片都放在了JLabel里面。

下面的代码完全符合您的需要。

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

}