1

I have an array of 64 JButtons and want to give them all hidden values of co-ordiantes which must stay the same. The text on the JButton will change according to what co-ordinate is chosen.

Is there a way to do this?

This is my code for putting text onto the buttons:

for (int j = 0; j < pieces.length; j++){

        for (int i = 0; i < pieces[j].length; i++){
            if (pieces[i][j] == null)
                contentPane.add(new JButton(" "));
            else {
                p = pieces[i][j].getChar();
                System.out.println(i + ","+j+","+p);
                contentPane.add(new JButton (Character.toString(p)));
            }
        }
    }
ChatNoir
  • 415
  • 8
  • 18

1 Answers1

2

Solution #1: Call setName on each button. A component's name is an arbitrary string which is not used by AWT or Swing at all, which means you are free to use it for your own purposes.

Solution #2: Since you have exactly 64 buttons, you can keep a separate 64-element array of data objects.

Solution #3: You can attach arbitrary data to any JComponent using putClientProperty. This is not a good solution as your code will be harder to understand and can break more easily. (Other code in other places has to "just know" to look for that specific client property, and has to "just know" what its type is.)

Solution #4: Subclass JButton and add the coordinate data to the subclass. This is not a good design, because you aren't creating a new kind of button component. There are better ways to associate data with a component.

VGR
  • 40,506
  • 4
  • 48
  • 63