Domanda

I am writing a sort of find me application where the user has to click on a certain area of the image to win the game. When the user clicks on the right location, I would like the image to update and display a yellow circle around the area.

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

public class findMe { 
static ImageIcon park = new ImageIcon("park.jpg");
static ImageIcon newPark = new ImageIcon("newPark.jpg");
static JLabel image = new JLabel(park);
static JPanel big = new JPanel();
static JLabel text = new JLabel("Clicks: 0");
static int i = 10;
static boolean winGame = false;

public static void main(String[] args) { 
    //Create the frame
    JFrame frame = new JFrame("Find Me");
    frame.setSize(935, 700); //Setting the size of the frame

    //Declaring the Mouse listener
    MouseHandler listener = new MouseHandler();

    big.add(image);
    big.add(text);

    image.addMouseListener(listener);

    JOptionPane.showMessageDialog (null, "Hint: Sometimes the head of beauty isn't as      bright as you'd think.");

    frame.getContentPane().add(big); //panel to frame 
    frame.setVisible(true); // Shows frame on screen
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} 

private static class MouseHandler implements MouseListener {

    public void mousePressed(MouseEvent e) {
        if (e.getX() >= 454 && e.getX() <= 480 && e.getY() >= 600 && e.getY() <= 625) {
            image = new JLabel(newPark);
            JOptionPane.showMessageDialog (null, "You've found it!");
            winGame = true;
        } else if (winGame == false) {
            i--;
            text.setText("Clicks left: " + i);
            if (i == 0) {
                System.exit(0);
            }
        }
    }

    public void mouseReleased(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }

    public void mouseClicked(MouseEvent e) {

    }
}    

}

The area of code that updates the image is:

if (e.getX() >= 454 && e.getX() <= 480 && e.getY() >= 600 && e.getY() <= 625) {
    image = new JLabel(newPark);
    JOptionPane.showMessageDialog (null, "You've found it!");
    winGame = true;
}

newPark is an edited version of the original image, with a yellow circle around the win area. Is this the proper way to redeclare and update the image? Because it's not working for me like this.

È stato utile?

Soluzione

Don't create a new instance of the image label, simple set the image label's icon property...

image.setIcon(newPark);

You may also want to read up on Initial Threads and the importance of creating your UI's within the context of the Event Dispatching Thread

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top