I'm on a project right now and I'm trying out some new code to make my program more efficient. I was thinking of an ArrayList
"dice" which will contain some buttons (that're supposed to be dice). If I for example array.add(die1)
, I assume I can refer to the object in the array instead of the actual button.
For example: I can set the text of die1 as die1.setText("");
I would also like to do it to the object in the array directly so I can use loops, like, array.get(i).setText("")
;
But it doesn't work which is weird. If I do array.get(0).getClass()
it says javax.Swing.JButton
which seems to be right.
Java 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
}
}
Expected: to work. But naturally it can't compile and crashes.
Because you haven't typed the declaration of your List.
Try this:
List<JButton> dice = new ArrayList<>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.