2

I am coding an image puzzle game and one part of the code is to compare the pieces the user has selected to the pieces of the correct image.

Each image piece is already added to a JButton as an ImageIcon.

An identifier is required to differentiate each image piece apart and also for comparision.

I am setting a setText() for each JButton created as the identifier.

But doing so will cause both the ImageIcon and setText to show up on the JButton.

Is there a way to hide the setText value and only display the ImageIcon ?

        private String id;
        private int cc;
        private JButton[] button = new JButton[9];

        cc += 1;
        id += ""+cc;

        for(int a=0; a<9; a++){
            // dd refers to the variable for the image pieces for each JButton
        button[a].setIcon(new ImageIcon( dd ));
        button[a].setText(id);
        }
iridescent
  • 305
  • 4
  • 14
  • 1
    You can use a _Map_ for storing each id for each button. So you can identify each button using this _Map_. Or you can use _setName_ for each button and for each image. – Amarnath Jan 19 '13 at 15:05
  • 1
    IMHO, instead of comparing `JButton`'s `images`, you can use an int `Array` having same size as that of `JButton` Array, and simply associate one number with each `ImageIcon`, hence you can compare this array values to get your desired result. Or instead of using `setText()` you can use [setName()](http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#setName(java.lang.String)), as an alternative for this approach. – nIcE cOw Jan 19 '13 at 15:12
  • 1
    2 interesting ways to do it, `Map` and `setName()` . Will read up on them :) – iridescent Jan 19 '13 at 16:00
  • Sorry for bringing up an old thread, but I do have issues obtaining the appropriate setName() for the buttons in the array which the user is supposed to drag the pieces to. http://stackoverflow.com/questions/14453513/comparing-components-via-setname Any further aid is appreciated :) – iridescent Jan 23 '13 at 02:30

1 Answers1

2

I recommend making another array of Strings:

String[] ids = new String[button.length];

And then button[a]'s ID would be ids[a].

Here is your code with the change:

    private String id;
    private int cc;
    private JButton[] button = new JButton[9];
    private String[] ids = new String[button.length];

    //cc += 1;
    //id += ""+cc;
    id += Integer.toString(++cc); //easier way

    for(int a=0; a<9; a++){
        // dd refers to the variable for the image pieces for each JButton
        button[a].setIcon(new ImageIcon( dd ));
        ids[a] = id;
    }
tckmn
  • 57,719
  • 27
  • 114
  • 156
  • Yeah I got that too, that's why the comment from me is gone +1 to the idea, provided by you :-) Though I still think you missed to add the thingy suggested by you in the modified code. – nIcE cOw Jan 19 '13 at 15:39