gpt4 book ai didi

java - 在 Java 中使用 for 循环创建按钮

转载 作者:行者123 更新时间:2023-11-30 03:07:37 24 4
gpt4 key购买 nike

我正在制作欧洲最 Alpine 脉的 map ,并希望创建一个 for 循环来为我执行按钮的操作。

我目前陷入了这段代码:

String Text = "btn" + i;
Text.addSelectionListener(new SelectionAdapter()

我想添加:

btn1.addSelectionListener(new SelectionAdapter()

btn2.addSelectionListener(new SelectionAdapter()

btn3.addSelectionListener(new SelectionAdapter()

btn4.....

运行 for 循环时。有谁知道该怎么做吗?

 for(final int i=1; i< country.length; i++){
String Text = "btn" + i;
Text.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {

txtCountry= new Text(shell, SWT.BORDER);
txtCountry.setText("Country: " + country[i]);
txtCountry.setBounds(22, 112, 204, 30);
formToolkit.adapt(txtCountry, true, true);

txtHighestMountain = new Text(shell, SWT.BORDER);
txtHighestMountain.setText("Highest Mountain: " + highestPoint[i]);
txtHighestMountain.setBounds(22, 148, 204, 30);
formToolkit.adapt(txtHighestMountain, true, true);

txtMeters = new Text(shell, SWT.BORDER);
txtMeters.setText("Meters above sea level: " + MAMSL[i]);
txtMeters.setBounds(22, 184, 204, 30);
formToolkit.adapt(txtMeters, true, true);
}
}

最佳答案

创建按钮数组:

Button[] btnArr = new Button[] {
btn1, btn2, btn3,...
}

&循环遍历它:

for(int i = 0; i < btnArr.length; i++) {
btnArr[i].addSelectionListener(new SelectionAdapter()....)
}

此外,要优化您的代码,请考虑创建自定义 SelectionListener

关于java - 在 Java 中使用 for 循环创建按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34354548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com