The method about ImageIcons does not work

一曲冷凌霜 提交于 2019-12-23 13:15:53

问题


import java.awt.*;
import java.awt.event.*;

import javax.swing.*;


public class Cards extends JFrame {

private GridLayout grid1;

    JButton []bt=new JButton[52];

    ImageIcon tail=new ImageIcon(getClass().getResource("b1fv.png"));

    ImageIcon ori;

    public Cards(){
        grid1=new GridLayout(7,9,2,2);
        setLayout(grid1);
        for(int i=0;i<bt.length;i++){
            ImageIcon c=new ImageIcon(getClass().getResource(i+1+".png"));
            bt[i]=new JButton(c);
            bt[i].addActionListener(new RatingMouseListener(i));
            add( bt[i]);
        }
    }

    public static void main(String[] args){
        Cards frame=new Cards();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1400,700);
        frame.setVisible(true);
    }

    private class RatingMouseListener implements ActionListener {
        private  int index=0;


        public RatingMouseListener(int index) {
            this.index = index;

        }




        public void actionPerformed(ActionEvent e) {
              System.out.println("Mouse entered for rating " + index);
            ori=new ImageIcon(getClass().getResource(index+1+".png"));

            if (bt[index].getIcon()==ori)
                bt[index].setIcon(tail);
             else
                bt[index].setIcon(ori);



        }

    }



}

When I run this, I expect that the ori and the tail should exchange. But they don't. Can someone help me?


回答1:


This would be best done via a description tag.

Basically, set the description to the images like below, then swap them if they have the same description.

ori.setDescription("ori");
tail.setDescription("tail");

if ("ori".equals((ImageIcon)bt[index].getIcon()).getDescription())
// The rest is how you had it.



回答2:


I'm guessing that you want to have playing cards that flip when clicked (but I'm not sure). Again, I recommend that you create your ImageIcons once and at the start of the program. Then you can easily compare if one icon is the same as another by using the equal(...) method or even in this situation the == operator. For example, please have a look at and run this code for an example of what I mean:

import java.awt.GridLayout;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

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

public class CardsDeck {
   public static final String RANKS = "a23456789tjqk";
   public static final String SUITS = "cdhs";
   public static final String CARDS_IMG_PATH = "http://math.hws.edu/javanotes/source/cards.png";
   private static final int BACK_RANK = 2;
   private static final int BACK_SUIT = SUITS.length();
   private static final String ICON = "icon";

   private JPanel panel = new JPanel();
   private List<ImageIcon> iconList = new ArrayList<ImageIcon>();
   private ImageIcon cardBack;

   public CardsDeck() {
      try {
         URL imgUrl = new URL(CARDS_IMG_PATH);
         BufferedImage img = ImageIO.read(imgUrl);

         double cardWidth = (double) img.getWidth() / RANKS.length();
         double cardHeight = (double) img.getHeight() / (SUITS.length() + 1);
         int w = (int) cardWidth;
         int h = (int) cardHeight;
         for (int rank = 0; rank < RANKS.length(); rank++) {
            for (int suit = 0; suit < SUITS.length(); suit++) {
               int x = (int) (rank * cardWidth);
               int y = (int) (suit * cardHeight);
               BufferedImage subImg = img.getSubimage(x, y, w, h);
               ImageIcon icon = new ImageIcon(subImg);
               iconList.add(icon);
            }
         }

         int x = (int) (BACK_RANK * cardWidth);
         int y = (int) (BACK_SUIT * cardHeight);
         BufferedImage subImg = img.getSubimage(x, y, w, h);
         cardBack = new ImageIcon(subImg);

         int hgap = 5;
         int vgap = hgap;
         panel.setLayout(new GridLayout(SUITS.length(), RANKS.length(), hgap, vgap));
         panel.setBorder(BorderFactory.createEmptyBorder(vgap, hgap, vgap, hgap));
         MouseListener mouseListener = new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
               JLabel label = (JLabel) e.getSource();
               Icon currentIcon = label.getIcon();
               if (currentIcon.equals(cardBack)) {
                  Icon icon = (Icon) label.getClientProperty(ICON);
                  label.setIcon(icon);
               } else {
                  label.setIcon(cardBack);
               }
            }
         };
         Collections.shuffle(iconList);
         for (int i = 0; i < iconList.size(); i++) {
            JLabel label = new JLabel(cardBack);
            label.putClientProperty(ICON, iconList.get(i));
            label.addMouseListener(mouseListener);
            panel.add(label);
         }
      } catch (MalformedURLException e) {
         e.printStackTrace();
         System.exit(-1);
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }
   }

   private JComponent getPanel() {
      return panel;
   }

   private static void createAndShowGui() {
      CardsDeck cardsDeck = new CardsDeck();

      JFrame frame = new JFrame("CardsDeck");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(cardsDeck.getPanel());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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

If run, it will show a 13 x 4 array of cards that can be flipped by clicking on them:



来源:https://stackoverflow.com/questions/13557561/the-method-about-imageicons-does-not-work

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