[英]Java: Updating a GUI element in an ArrayList
I have to create a game for my final Java school assignment. 我必须为最终的Java学校作业创建一个游戏。 In it I'm populating a
JPanel
with custom made "Peg" objects that extend JComponent
in a for loop. 在其中,我用一个在循环中扩展
JComponent
定制“ Peg”对象填充了一个JPanel
。 The JPanel
uses a GridBagLayout
. JPanel
使用GridBagLayout
。 Inside the for loop I add the "Peg" objects to an ArrayList
, and then get the element from that ArrayList
and add it to the JPanel
. 在for循环中,我将“ Peg”对象添加到
ArrayList
,然后从该ArrayList
获取元素并将其添加到JPanel
。 This is all done in a method that looks like this: 这都是通过如下方法完成的:
public void createDummyPegs()
{
for (int i = 0; i < 13; i++)
{
initPegsArray.add(new ArrayList<>());
dummyPegsConstraints.gridy = i;
for (int j = 0; j < 5; j++)
{
dummyPegsConstraints.gridx = j;
if (i == 0)
{
tempColorPeg = new ColorPeg(Color.DARK_GRAY);
initPegsArray.get(i).add(j, tempColorPeg);
pegsLeftPanel.add((JComponent) initPegsArray.get(i).get(j),
dummyPegsConstraints);
}
else
{
tempDummyPeg = new DummyPeg();
initPegsArray.get(i).add(j, tempDummyPeg);
pegsLeftPanel.add((JComponent) initPegsArray.get(i).get(j),
dummyPegsConstraints);
}
}
}
}
This works fine, and it generates a grid of these "Peg" objects nicely. 这可以正常工作,并且可以很好地生成这些“钉”对象的网格。 Here's the problem: I have a button that ideally is supposed to replace one of these "Peg" objects with another "Peg" object of a different color.
问题出在这里:我有一个按钮,理想情况下,该按钮应将这些“钉子”对象之一替换为另一种颜色不同的“钉子”对象。 When I click on the button I:
当我单击按钮时,我:
ArrayList
, let's the first one; ArrayList
删除一个元素,让我们成为第一个元素; Alternatively, I've tried using the set()
method to just update the element in the given position with the new "Peg". 另外,我尝试使用
set()
方法仅使用新的“ Peg”更新给定位置的元素。 The thing is that when I add the new "Peg" element, it seems that it is not initialized with a size. 问题是,当我添加新的“ Peg”元素时,似乎未使用大小对其进行初始化。 Sending this new "Peg" to a
System.out.println()
statement to read what's inside of it, it prints out: 将这个新的“ Peg”发送到
System.out.println()
语句以读取其中的内容,它会打印出:
com.rburgos.mastermindtestlayout.ColorPeg[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minimumSize=,preferredSize=]
I don't understand why the first time I add to the ArrayList
it works, but the second time it doesn't. 我不明白为什么我第一次添加到
ArrayList
时起作用,但是第二次却不起作用。
Any tips of guidance will be greatly appreciated. 任何指导技巧将不胜感激。 Here's the full code if that helps:
如果有帮助,请参见以下完整代码:
I feel silly, but I think I was able to figure it out. 我觉得很傻,但是我想我能够弄清楚。 After adding a new "Peg" to the array and passing that to the JPanel, I was calling
update()
. 在向数组添加新的“ Peg”并将其传递给JPanel之后,我正在调用
update()
。 By calling revalidate()
now the new "Peg" gets added to the panel. 通过现在调用
revalidate()
,新的“钉”将添加到面板中。 Hopefully this will help others with a similar problem. 希望这可以帮助其他有类似问题的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.