user3111762
user3111762

Reputation: 23

Change ImageIcon during

I have two questions:

  1. I'm creating a simple memory game that save a random sequence and expect the same input from player, and i'm trying to change an JButton ImageIcon when clicked to a brighter version of the img1 using the setIcon() but nothing change during run-time.

    private final JButton btnImg1 = new JButton("");
    ImageIcon img1 = new ImageIcon("C:\\Users\\vide\\Desktop\\img1.png");
    ImageIcon img1_b = new  ImageIcon("C:\\Users\\vide\\Desktop\\img1_b.png");
    
    try {
         btnImg1.setIcon(img1);
         Thread.sleep(2000);
         btnImg1.setIcon(img1_b);
     }
    
  2. I made 2 int Lists to save the inputs and the random sequence, cause of the dynamic size:

    List<Integer> seqAlea =  new ArrayList<Integer>();
    List<Integer> seqInsere =  new ArrayList<Integer>();
    int placar = 0;
    
    Random geraNumero = new Random();
    
    public void comecaJogo(){
    
        for(int i = 0; i < 3; i++){
            int numero = geraNumero.nextInt(4) + 1;             
            seqAlea.add(i, numero);
        }
    }
    

There is a better way to do it?

Upvotes: 0

Views: 484

Answers (1)

Gabriel C&#226;mara
Gabriel C&#226;mara

Reputation: 1249

First of all, NEVER use a sleep in your main thread if you don't mean to block it, this will make your application wait until the sleep is over, thus "blocking" your main thread.

  1. For your first question, this code would solve:

    // Assuming that your image will be within your package
    final URL resource = getClass().getResource("/com/mypackage/myimage.png");
    
    final JButton btn = new JButton("My Button");
    final Image image = ImageIO.read(resource);
    final ImageIcon defaultIcon = new ImageIcon(image);
    
    btn.setIcon(defaultIcon);
    btn.addActionListener(new ActionListener() {
    
        public void actionPerformed(ActionEvent e) {
            try {
                //This will do the trick to brighten your image
                Graphics2D g2 = (Graphics2D) image.getGraphics();
    
                // Here we're creating a white color with 50% of alpha transparency
                g2.setColor(new Color(255, 255, 255, 50));
                // Fill the entire image with the new color
                g2.fillRect(0, 0, defaultIcon.getIconWidth(), defaultIcon.getIconHeight());
                g2.dispose();
                btnBtn.setIcon(new ImageIcon(image));
            } catch (Exception ex) {
                /*Although this is a bad practice, my point here is not 
                 * to explain exceptions. 
                 * But it's a good practice to always capture as many exceptions as you can
                */
            }
        }
    });
    
  2. Well, you don't actually NEED to explicitely inform in which position you're adding the element, specially if it's a sequence. Arraylists don't sort items.

Upvotes: 2

Related Questions