第二次单击该按钮时,图像不会改变

时间:2014-09-20 12:58:50

标签: java image swing user-interface jframe

所以我在这里有一个代码,它就像游戏模拟人生,你可以改变你的模拟人或人的外观。所以我的问题是,一旦我在组合框中选择了一个选项,一旦我点击加载按钮,图像就会改变。但是一旦我点击另一个选择因为我想要改变它,图像就不会再改变了。这是代码。我将提供我使用的照片的链接。以下是图片的下载链接:https://onedrive.live.com/redir?resid=ED1942ABAA45D6A5%21245以及代码。

 import javax.swing.*;
  import java.awt.event.*;
  import java.awt.*;
  import javax.swing.JTextArea;


  public class Sims extends JFrame {
  private int x,y,z;
  private Container game;
  private JComboBox Head;
  private JComboBox Ear;
  private JLabel Avatar;
  private JTextArea details;

  private String []Hat = {"No Hat", "Captain Hat", "Black Leather Hat"};
  private JButton load;
  private String []Earrings = {"No Earrings", "Silver Dangling Earrings", "Gold Dangling      Earrings"};
  private ImageIcon [] Accessories =
  { new ImageIcon("blackleather.PNG"),//0
    new ImageIcon("blackleather_goldear.PNG"),//1
    new ImageIcon("blackleather_silverear.PNG"),//2
    new ImageIcon("captainhat.PNG"),//3
    new ImageIcon("captainhat_goldear.PNG"),//4
    new ImageIcon("captainhat_silverear.PNG"),//5
    new ImageIcon("goldear.PNG"),//6
    new ImageIcon("noaccessories.PNG"),//7
    new ImageIcon("silverear.PNG")};//8

  public Sims() {
  getContentPane().removeAll();
   setTitle("Avatar!");
   setSize(250,450);
   setLocationRelativeTo(null);
   game = getContentPane();
   game.setLayout(new FlowLayout());
   Head = new JComboBox(Hat);
   Ear = new JComboBox(Earrings);
   Avatar = new JLabel(Accessories[7]);
   load = new JButton("Load Image");
   details = new JTextArea("AVATAR DETAILS:               "+"\n"+"     Hat:            "+Hat[Head.getSelectedIndex()]+"\n"+"     Earrings:   "+Earrings[Ear.getSelectedIndex()]);
game.add(Avatar);
game.add(Head);
game.add(Ear);
game.add(load);
game.add(details, BorderLayout.SOUTH);
setVisible(true);
details.setEditable(false);

Head.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e){
        JComboBox temphead = (JComboBox) e.getSource();
        int temphat = (int) temphead.getSelectedIndex();
        x = temphat;
    }
});
Ear.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e){
        JComboBox tempear = (JComboBox) e.getSource();
        int tempearrings = (int) tempear.getSelectedIndex();
        y = tempearrings;
    }
});
load.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e){
    getContentPane().removeAll();
    if(x==0&&y==0){
        z = 7;
    }
    if(x==0&&y==1){
        z = 8;
    }
    if(x==0&&y==2){
        z = 6;
    }
    if(x==1&&y==0){
        z = 3;
    }
    if(x==1&&y==1){
        z = 5;
    }
    if(x==1&&y==2){
        z = 4;
    }
    if(x==2&&y==0){
        z = 0;
    }
    if(x==2&&y==1){
        z = 2;
    }
    if(x==2&&y==2){
        z = 1;
    }


    setTitle("Avatar");
    setSize(250,450);
    setLocationRelativeTo(null);
    game = getContentPane();
    game.setLayout(new FlowLayout());
    Head = new JComboBox(Hat);
    Ear = new JComboBox(Earrings);
    Avatar = new JLabel(Accessories[z]);
    load = new JButton("Load Image");

    details = new JTextArea("AVATAR DETAILS:               "+"\n"+"     Hat:            "+Hat[x]+"\n"+"     Earrings:   "+Earrings[y]);
    game.add(Avatar);

    game.add(Head);
    game.add(Ear);

    game.add(load);
    game.add(details, BorderLayout.SOUTH);
    setVisible(true);
    details.setEditable(false);

    }
    });



}


   public static void main(String[] args) {
   Sims fs = new Sims();

       fs.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


   }

   }

1 个答案:

答案 0 :(得分:1)

当按下JButton时,您正在加载全新的组件,因此新组件的响应与旧组件不同。不要那样做。而是在ActionLIstener中只需更改现有显示JLabel的图标,就是这样。

重申一下,你的JButton的ActionListener应该从JComboBoxes获取数据(不需要给组合框ActionListeners),然后交换图标,就是这样。它不应该创建新的组件。

底线是你的JButton的半伪代码中的ActionListener看起来像这样:

  @Override
  public void actionPerformed(ActionEvent e) {
     // get earrings selection from earrings combo box
     // get hat selection from hat combo box

     avatarLabel.setIcon(.... some value based on the selections abovbe ...);
  }

我自己,我发现最简单的方法是创建两个枚举,一个Hat枚举和一个Earrings枚举,然后创建一个包含这两个枚举值的Head类,并且重要的是覆盖Object的equals和hashCode方法,这样它才能很好地工作。一个HashMap。然后,我将每个Head对象与HashMap中的ImageIcon相关联,并在我的ActionListener中使用此HashMap选择正确的图标。这对你来说有点过度杀戮,我怀疑你可以将它用于你的任务,但无论如何,这里是:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

public class ImageSwap extends JPanel {
   private Map<Head, Icon> headIconMap = new HashMap<>();
   private JComboBox<Earrings> earingCombo = new JComboBox<>(Earrings.values());
   private JComboBox<Hat> hatCombo = new JComboBox<>(Hat.values());
   private JButton loadButton = new JButton(new LoadAction("Load", KeyEvent.VK_L));
   private JLabel avatarLabel = new JLabel();

   public ImageSwap() throws IOException {
      addToMap("blackleather.PNG", Earrings.NONE, Hat.BLACK_LEATHER);
      addToMap("blackleather_goldear.PNG", Earrings.GOLD, Hat.BLACK_LEATHER);
      addToMap("blackleather_silverear.PNG", Earrings.SILVER, Hat.BLACK_LEATHER);
      addToMap("captainhat.PNG", Earrings.NONE, Hat.CAPTAIN);
      addToMap("captainhat_goldear.PNG", Earrings.GOLD, Hat.CAPTAIN);
      addToMap("captainhat_silverear.PNG", Earrings.SILVER, Hat.CAPTAIN);
      addToMap("goldear.PNG", Earrings.GOLD, Hat.NONE);
      addToMap("noaccessories.PNG", Earrings.NONE, Hat.NONE);
      addToMap("silverear.PNG", Earrings.SILVER, Hat.NONE);

      avatarLabel.setIcon(headIconMap.get(new Head(Earrings.NONE, Hat.NONE)));

      JPanel buttonComboPanel = new JPanel(new GridLayout(0, 1, 0, 5));
      buttonComboPanel.add(earingCombo);
      buttonComboPanel.add(hatCombo);
      buttonComboPanel.add(loadButton);

      setLayout(new BorderLayout());
      add(avatarLabel, BorderLayout.CENTER);
      add(buttonComboPanel, BorderLayout.PAGE_END);
   }

   private void addToMap(String resourceText, Earrings earrings, Hat hat)
         throws IOException {
      BufferedImage img = ImageIO.read(getClass().getResource(resourceText));
      Icon icon = new ImageIcon(img);
      headIconMap.put(new Head(earrings, hat), icon);
   }

   private class LoadAction extends AbstractAction {
      public LoadAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         Earrings selectedEarrings = (Earrings) earingCombo.getSelectedItem();
         Hat selectedHat = (Hat) hatCombo.getSelectedItem();

         if (selectedEarrings != null && selectedHat != null) {
            avatarLabel.setIcon(headIconMap.get(new Head(selectedEarrings, selectedHat)));
         }
      }
   }

   private static void createAndShowGui() {
      ImageSwap mainPanel;
      try {
         mainPanel = new ImageSwap();
         JFrame frame = new JFrame("ImageSwap");
         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         frame.getContentPane().add(mainPanel);
         frame.pack();
         frame.setLocationByPlatform(true);
         frame.setVisible(true);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

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

class Head {
   Earrings earrings;
   Hat hat;

   public Head(Earrings earrings, Hat hat) {
      this.earrings = earrings;
      this.hat = hat;
   }

   public Earrings getEarrings() {
      return earrings;
   }

   public Hat getHat() {
      return hat;
   }

   @Override
   public int hashCode() {
      final int prime = 31;
      int result = 1;
      result = prime * result + ((earrings == null) ? 0 : earrings.hashCode());
      result = prime * result + ((hat == null) ? 0 : hat.hashCode());
      return result;
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (obj == null)
         return false;
      if (getClass() != obj.getClass())
         return false;
      Head other = (Head) obj;
      if (earrings != other.earrings)
         return false;
      if (hat != other.hat)
         return false;
      return true;
   }

}

enum Earrings {
   NONE("No Earrings"), SILVER("Silver Dangling Earrings"), GOLD(
         "Gold Dangling Earrings");
   private String text;

   private Earrings(String text) {
      this.text = text;
   }

   @Override
   public String toString() {
      return text;
   }
}

enum Hat {
   NONE("No Hat"), CAPTAIN("Captain Hat"), BLACK_LEATHER("Black Leather Hat");
   private String text;

   private Hat(String text) {
      this.text = text;
   }

   @Override
   public String toString() {
      return text;
   }
}