user3767918
user3767918

Reputation: 63

The image will not change when the button is clicked for the second time

So I have here a code, it is like the game Sims where you change the appearance of your sim or the person. So my problem is that once I choose a selection on the combo box, the image will change once i click the load button. But once I click another selection because I want to change it, the image will not change anymore. here is the code. I will provide the link of the photos that i used. Here's the download link of the images : https://onedrive.live.com/redir?resid=ED1942ABAA45D6A5%21245 so as the code too.

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


   }

   }

Upvotes: 1

Views: 179

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285401

You're loading completely new components when the JButton is pressed, and so the new components will not respond the same as the old ones. Don't do that. Instead within the ActionLIstener simply change the icon of the existing display JLabel, and that's it.

To reiterate, your JButton's ActionListener should get the data from the JComboBoxes (no need to give the combo boxes ActionListeners) and then swap icons, and that's it. It should create no new components.

The bottom line is that your JButton's ActionListener in semi-pseudo code should look something like this:

  @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 ...);
  }

Myself, I found it easiest to create two enums, a Hat enum and an Earrings enum, then create a Head class that holds the values of these two enums, and importantly overrides Object's equals and hashCode methods so it will work well in a HashMap. I then associate each Head object with an ImageIcon in a HashMap, and in my ActionListener select the correct icon using this HashMap. This is a bit of over-kill for you, and I doubt that you can use it for your assignment, but regardless, here it is:

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

Upvotes: 1

Related Questions