【问题标题】:How to set text for a bunch of JButton from another JFrame with loop?如何使用循环从另一个 JFrame 为一堆 JButton 设置文本?
【发布时间】:2018-05-26 16:25:05
【问题描述】:

我在 JFrame 的网格中有 36 个 JButton 组件,并希望在我从另一个框架上的菜单打开框架时将它们的文本设置为 1、2、3 ... 36。 (稍后我必须随机化他们的数字。)

按钮名称相似:

jButton1
jButton2
jButton3
...
jButton35
jButton36

简单地将第一个按钮文本更改为 1 是:

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

有这样的方法吗?:

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);
}

我找到了这些链接,但它们并不是很有用,因为我的按钮不在任何数组或列表中,并且它们正在更改同一框架中的文本,或者没有其他方法吗?:

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?

【问题讨论】:

  • 1) “我从另一个框架上的菜单打开框架” 请参阅The Use of Multiple JFrames, Good/Bad Practice? 2) 为获得更好的帮助,请尽快发布minimal reproducible example 或@987654326 @。 3) “它们不是很有用,因为我的按钮不在任何数组或列表中” 所以.. 把它们放在一个'数组中或列出'!
  • 我投票决定将此问题作为离题结束,因为 OP 已经确定并排除了问题的解决方案。
  • Later I have to randomize their number.) - 使用 ArrayList 的另一个原因。您创建 36 个带有文本的按钮。然后你可以使用 Collections.shuffle(...) 来随机化按钮。然后您只需遍历列表并将按钮添加到网格中。

标签: java swing loops jframe jbutton


【解决方案1】:

创建一个 JButton 类型的 ArrayList,将 JButton 添加到其中,并使用 for-each 循环进行迭代并赋值。这段代码对我有用。

    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++;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多