I have to create a game for my final Java school assignment. In it I'm populating a JPanel
with custom made "Peg" objects that extend JComponent
in a for loop. The JPanel
uses a 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
. 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; Alternatively, I've tried using the set()
method to just update the element in the given position with the new "Peg". The thing is that when I add the new "Peg" element, it seems that it is not initialized with a size. Sending this new "Peg" to a System.out.println()
statement to read what's inside of it, it prints out:
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.
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()
. By calling revalidate()
now the new "Peg" gets added to the panel. Hopefully this will help others with a similar problem.
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.