关于ImageIcons的方法不起作用

时间:2012-11-26 01:36:17

标签: java swing actionlistener imageicon

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



        }

    }



}

当我跑这个时,我希望ori和尾巴应该交换。但他们没有。有人能帮助我吗?

2 个答案:

答案 0 :(得分:3)

最好通过description代码完成。

基本上,将描述设置为如下图像,如果它们具有相同的描述,则交换它们。

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

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

答案 1 :(得分:2)

我猜你想要点击时翻转的牌(但我不确定)。同样,我建议您在程序开始时创建一次ImageIcons。然后,通过使用等(...)方法或甚至在这种情况下==运算符,您可以轻松地比较一个图标是否与另一个图标相同。例如,请查看并运行此代码以获取我的意思的示例:

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

如果运行,它会显示一个13 x 4的卡片阵列,可以通过点击它们来翻转:

enter image description here