0

I have 36 JButton components in a grid on a JFrame, and wish to set their text to 1, 2, 3 ... 36 when I open the frame from a menu which is on another frame. (Later I have to randomize their number.)

The buttons have similar names:

jButton1
jButton2
jButton3
...
jButton35
jButton36

To simply change the first button text to 1 is:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    grid gr = new grid();
    grid.jButton1.setText("1");
    gr.setVisible(true);
}

Is there a way something like this?:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
    grid gr = new grid();
    String number;

    for (int i=1; i<37; i++) {
        number=Integer.toString(i);
        grid.jButton<i>.setText(number);
    }
    gr.setVisible(true);
}

I have found these links but they weren't very useful since my buttons are not in any array or list and they are changing texts from the same frame, or is there no other way?:

Assigning variables with dynamic names in Java

How to give each JButton in a 10 x 10 grid button layout a unique ID/name

How to rename set of JButtons?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Dodande
  • 97
  • 5
  • 1
    1) *"I open the frame from a menu which is on another frame"* See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 2) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 3) *"they weren't very useful since my buttons are not in any array or list"* So .. ***put them*** in an 'array or list'! – Andrew Thompson May 26 '18 at 16:33
  • 1
    I'm voting to close this question as off-topic because the OP has both identified and ruled out the solution to the problem. – Andrew Thompson May 26 '18 at 16:34
  • `Later I have to randomize their number.)` - another reason for using an ArrayList. You create 36 buttons with there text. Then you can use Collections.shuffle(...) to randomize the buttons. Then you simply iterate through the list and add the buttons to the grid. – camickr May 26 '18 at 16:42

1 Answers1

0

Create an ArrayList of type JButton, add JButton to it, and iterate using for-each loop and assign values. This code works for me.

    JFrame frame = new JFrame();
    frame.setSize(400, 500);
    frame.setVisible(true);
    frame.setLayout(null);

    ArrayList<JButton> buttons = new ArrayList<JButton>();
    JButton b1= new JButton();
    JButton b2= new JButton();
    JButton b3= new JButton();
    JButton b4= new JButton();
    JButton b5= new JButton();

    buttons.add(b1);
    buttons.add(b2);
    buttons.add(b3);
    buttons.add(b4);
    buttons.add(b5);
    int count = 1;
    for(JButton b: buttons)
    {
        b.setText(String.valueOf(count));
        b.setBounds(0,count*50,50,30);
        frame.add(b);
        count++;
    }