所以我的代码在JPanel上垂直打印玩家姓名和分数,首先是所有玩家,然后是他们的所有分数。我想知道如何在他们的分数旁边一个接一个地打印。例如,
Name1 Score1
Name2 Score2
Name3 Score3
Name4 Score4
我的代码是为前10名球员/分数制作的,所以我使用数组来实现这个方法。我的代码是:
for (int x = 0; x < 10; x++)
{
JSingleplayer[x] = new JLabel (Singleplayer[x]);
EndPanelplayer.add(JSingleplayer[x],BorderLayout.EAST);
JSingleScore[x] = new JLabel (SingleScore[x]);
EndPanelscore.add(JSingleScore[x],BorderLayout.WEST);
}
EndFrame.add(EndPanelplayer);
EndFrame.add(EndPanelscore);
如你所见,我有两个面板。我把一个往东一个往西,但没用。我也试着往南走。我需要帮助修复我的代码或添加额外的代码,以便与它的伴侣垂直打印。提前感谢!
我会用JTable
请参阅Swing教程中关于如何使用表的部分,以获得更多信息和工作示例。
还要遵循Java命名约定。变量名不能以大写字符开头
每当您想要对齐标签和/或字段时,您首先想到的应该是使用griddbaglayout。
您还应该使用小写字母开始Java字段。以下是Java的命名约定。
这是你的代码。您需要在定义JPanel时设置布局。
private static final Insets bottomInsets =
new Insets(0, 0, 6, 0);
private void addLabels() {
int gridy = 0;
for (int x = 0; x < 10; x++) {
jSingleplayer[x] = new JLabel(singleplayer[x]);
addComponent(mainPanel, jSingleScore[x], 0, gridy, 1, 1,
bottomInsets, GridBagConstraints.LINE_START,
GridBagConstraints.NONE);
jSingleScore[x] = new JLabel(singleScore[x]);
addComponent(mainPanel, jSingleScore[x], 1, gridy++, 1, 1,
bottomInsets, GridBagConstraints.LINE_START,
GridBagConstraints.NONE);
}
}
private void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight,
Insets insets, int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 1.0D, 1.0D, anchor, fill,
insets, 0, 0);
container.add(component, gbc);
}