我有一个List,在其ListCellRenderer类中,我将Labels显示为“Labels”和数据值。
问题在于,如果列表中有多个元素,则标签未对齐,则它们的宽度不同。虽然我使用了以下代码,但它没有做任何事情:
public CListCell(boolean displayPhoto, String[] libelles)
{
showPhoto = displayPhoto;
if (displayPhoto)
{
setLayout(new BorderLayout());
addComponent(BorderLayout.WEST, pic);
}
else
setLayout(new GridLayout(1,1));
labels = new Label[libelles.length];
lData = new Label[libelles.length+1];
for (int i=0;i<libelles.length+1;i++)
{
lData[i] = new Label("");
lData[i].setAlignment(Label.LEFT);
lData[i].getStyle().setMargin(Component.TOP, 1);
lData[i].getStyle().setMargin(Component.BOTTOM, 1);
lData[i].getStyle().setPadding(0, 0, 0, 0);
if (i == libelles.length)
break;
labels[i] = new Label(libelles[i]);
labels[i].setAlignment(Label.LEFT);
labels[i].getStyle().setMargin(Component.TOP, 1);
labels[i].getStyle().setMargin(Component.BOTTOM, 1);
labels[i].getStyle().setPadding(0, 0, 0, 0);
}
cRow21.addComponent(labels[0]);
cRow21.addComponent(lData[1]);
cRow22.addComponent(labels[1]);
cRow22.addComponent(lData[2]);
cRow2.addComponent(BorderLayout.WEST, cRow21);
cRow2.addComponent(BorderLayout.EAST, cRow22);
cRow1AndRow2.addComponent(lData[0]);
cRow1AndRow2.addComponent(cRow2);
if (displayPhoto)
addComponent(BorderLayout.CENTER, cRow1AndRow2);
else
addComponent(cRow1AndRow2);
focus.setUIID("bandeau_selection_list");
this.getStyle().setBgPainter(new LigneHorizontalPainter(this, 0));
}
public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected)
{
Content entry = null;
Image thumb;
int[] tLibImpayesLength = new int[list.size()];
int maxDataLength;
if (value instanceof Content)
entry = (Content)value;
if (entry != null)
{
if (showPhoto)
{
thumb = createThumbnail(entry.getPhoto(), entry.getColumn(4));
pic.setIcon(thumb);
}
lData[0].setText(Formatage.nvl(entry.getColumn(1),"-"));
lData[1].setText(Formatage.nvl(entry.getColumn(2),"-"));
lData[2].setText(Formatage.nvl(entry.getColumn(3),"-")); // lData[2] is the Label which displays value at the right side of the Container , the others are at the above,left and do not cause any problem
tLibImpayesLength[index] = lData[2].getText().length();
}
maxDataLength = Formatage.max(tLibImpayesLength);
if (lData[2].getText().length() < maxDataLength)
{
lData[2].setPreferredW(maxDataLength);
}
list.repaint();
return this;
}
以下是运行时捕获的图像:
当我们查看图片时,我们会看到Impayé (Ar)
标签及其右侧的剩余值未对齐。那么如何使它们垂直对齐,或者具有相同的宽度?
答案 0 :(得分:0)
你没有在你发布的代码中包含你布置组件的方式,你也调用了setPreferredW(),这有效地破坏了布局,所以这显然是一个错误。
通常要实现类似的东西,将左侧标签放在框布局Y中,并将其放置在边框布局的CENTER中。将右侧标签放在该边框布局的EAST侧。