Skip to content
Advertisement

JFrame Image Update on click of image

tldr; How do you use a MouseEvent on a JFrame object(specifically JLabel) to update the displayed image in the JFrame

I am trying to create a program where an image is broken into tiles and on click of one of those tiles, the program moves the tile to the open space in the image. (See Sliding Puzzle for more information).

I currently am able to select an image, break the image into tiles, and “randomly” remove one of the tiles.

My next step would be, on click of one of the tiles, to swap it with the empty tile (I will work on the “eligibility” of tiles to be swapped at a later time, but for now, just want to be able to swap the tile selected with the current blank tile)

To create my image for a 3×3 grid, I split a bufferedImage into 9 equal pieces, “randomly” blank one of the images, and then display the images in jLabels using GridLayout to line them up.

When I add mouseListeners to each jLabel, I am able to see that I am entering the MouseListener as I can see the console log message “Clicked” as shown below, however, am not able to update the image as desired.

How can I use a MouseEvent on these JFrame JLabels to call a method within ImageContainer(i.e. move()) and update the displayed image?

JavaScript
JavaScript

Advertisement

Answer

Don’t remove/add components. Instead just swap the Icon.

  1. Use a JPanel with a GridLayout that contains a JLabel in each grid
  2. Add an ImageIcon to each JLabel (except for one)
  3. Add a MouseListner to each JLabel.
  4. In the mouseClicked event you get the label that was clicked and remove the ImageIcon and add the Icon to the empty label.

So when you create the board you could have a variable like emptyLabel which would be initialized to the label without the Icon. Then the logic in the mouseClicked might be something like:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement