java - 由 JButton 组成的 ArrayList。但没有按预期工作
问题描述
我现在正在进行一个项目,我正在尝试一些新代码以使我的程序更有效率。我在想一个ArrayList
“骰子”,它将包含一些按钮(应该是骰子)。例如array.add(die1)
,如果我假设我可以引用数组中的对象而不是实际的按钮。
例如:我可以设置 die1 的文本,因为die1.setText("");
我也想直接对数组中的对象进行设置,这样我就可以使用循环,比如,array.get(i).setText("")
;
但它不起作用,这很奇怪。如果我这样做array.get(0).getClass()
,它会说javax.Swing.JButton
这似乎是正确的。
爪哇 11
ArrayList dice = new ArrayList<JButton>();
private void die1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (die1.getBackground() == Color.red) {
dice.remove(dice.indexOf(die1));
die1.setBackground(Color.green);
}
else {
dice.add(die1);
die1.setBackground(Color.red);
}
}
private void btnRollActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
for (int i = 0; i < dice.size(); i++) {
int random = roll();
dice.get(i).setText(""+random); //This displays as error; uncompilable
}
}
预期:工作。但自然它无法编译并崩溃。
解决方案
因为你还没有输入你的列表的声明。
尝试这个:
List<JButton> dice = new ArrayList<>();
推荐阅读
- c# - 如何在 FlowEnt 中开始补间
- php - Nginx 与 FPM 和 Laravel
- python - 如何使一组机器人向一个方向移动而不发生碰撞
- jupyter-notebook - Kaggle notebook 一个单元格中的多个命令?
- android - 打开浏览器意图抛出异常
- python - 如何将 api.Response 转换为 python 中的数据框或 json?
- npm-install - Angular npm install 安装在不同的目录中,而不是 package.json 所在的当前目录
- reactjs - 无法在 jsx 组件中按地图显示产品
- mysql - 使用nodeJS比较来自MYSQL数据库的哈希密码时无法登录
- azure - 托管在 azure 文件存储上的几分钟后音频停止播放