简体   繁体   English

如何通过循环从另一个JFrame为一堆JButton设置文本?

[英]How to set text for a bunch of JButton from another JFrame with loop?

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. 我在JFrame的网格中有36个JButton组件,当我从另一个框架上的菜单中打开框架时,希望将其文本设置为1、2、3 ... 36。 (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: 只需将第一个按钮的文本更改为1即可:

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 在Java中使用动态名称分配变量

How to give each JButton in a 10 x 10 grid button layout a unique ID/name 如何为10 x 10网格按钮布局中的每个JButton提供唯一的ID /名称

How to rename set of JButtons? 如何重命名一组JButton?

Create an ArrayList of type JButton, add JButton to it, and iterate using for-each loop and assign values. 创建类型为JButton的ArrayList,向其添加JButton,然后使用for-each循环进行迭代并分配值。 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++;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM