我正在使用Java和GridBagLayout重新创建图像中显示的窗体。为了在一周内创建网格线,我将带有边框的空JLabel插入到空单元格中。这对我来说非常合适,然后我决定让每个在表单上加阴影的空单元格都用java着色,这就是我挣扎的地方。在我for循环中发现逻辑错误
我的想法是,我可以创造一个“绿荫指针”像我和我的X和Y坐标一样,这shadePtr将与8值开始,因为这是第一个行进行shadded,当循环遮住一行时,它会将shadePtr增加3,因为行11是下一个被着色,然后是14,依此类推。
到目前为止,我得到的唯一一点成功是如果我注释掉你看到的最后一行代码(shadePtr = shadePtr + 3),但是只有一行被遮蔽。我似乎无法弄清楚什么我在这里做错了,并会感谢您的时间和精力。
int yPointer = 7;
int xPointer = 3;
int shadePtr = 8;
for (int j = 0; j <= 299; j++)
{
gbc.gridx = xPointer;
gbc.gridy = yPointer;
gbc.gridheight = 1;
gbc.gridwidth = 1;
if (yPointer == 36) calendarGridLines[j].setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Color.BLACK)); //if bottom row
else calendarGridLines[j].setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.BLACK));
if (yPointer == shadePtr){ //if row number = shadePtr then color the cell
calendarGridLines[j].setOpaque(true);
calendarGridLines[j].setBackground(Color.GRAY);
}
gridbag.setConstraints(calendarGridLines[j], gbc);
rp.add(calendarGridLines[j]);
xPointer++; //go to next cell in row
j++; //use the next jlabel
gbc.gridx = xPointer;
gbc.gridy = yPointer;
gbc.gridheight = 1;
gbc.gridwidth = 1;
if (yPointer == 36) calendarGridLines[j].setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK)); //if bottom row
else calendarGridLines[j].setBorder(BorderFactory.createMatteBorder(1, 1, 0, 1, Color.BLACK));
if (yPointer == shadePtr){ //if row number = shadePtr then color the cell
calendarGridLines[j].setOpaque(true);
calendarGridLines[j].setBackground(Color.GRAY);
}
gridbag.setConstraints(calendarGridLines[j], gbc);
rp.add(calendarGridLines[j]);
xPointer++; //go to next cell in row
if(xPointer == 13) //if end of column then go to next row and reset column pointer to 3 and increment shade pointer by 3
{
yPointer++; //go down a row
xPointer = 3;
shadePtr = shadePtr + 3; //when this line is commented out, one row will be colored; when active none are colored
}
}
感谢@ dic19,您的解决方案工作。但是为了我自己的理解,你能回答这个问题吗?你说我的shadePtr每迭代增加3次,但是我认为通过在最后一个else语句中增加shadePtr 3,只有当我到达结尾时该行应该将我的新shadePtr设置为11,这是我希望下一行被遮挡的位置。我的推理出了什么问题? –
哦等一下,它刚刚在我身上发现。我必须仔细阅读你的解释才能沉入其中。再次感谢!精彩的解释。 –
@solleks欢迎您!很高兴帮助你。理解这有点棘手,但认为你得到它:) – dic19