我有一个以随机顺序填充复合 Material 的 GridLayout。现在,我正在对填充列表/集合中的 GridLayout 的复合 Material 进行排序,并希望像我的列表/集合中的排序结果一样对它们进行排序。我试图通过再次将它们分配给它们的 parent 来做到这一点,以便它们按正确的顺序排列,但由于某种原因什么也没发生。然后我尝试将它们缓存在您看不到的 Composite 中,然后使用与第一次尝试相同的方法将它们带回父级。完全没有变化。有人有指针吗?我按日期订购,以防万一/所以想知道。
这就是我的网格的样子,现在我想像在我的 arrayList() 中一样对它们进行排序;
最佳答案
您正在寻找的方法是 Control#moveAbove(Control control)
和 Control#moveBelow(Control control)
来重新排序项目:
private static List<Label> labels = new ArrayList<Label>();
private static List<Color> colors = new ArrayList<Color>();
public static void main(String[] args)
{
Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Stackoverflow");
shell.setLayout(new RowLayout(SWT.VERTICAL));
colors.add(display.getSystemColor(SWT.COLOR_BLUE));
colors.add(display.getSystemColor(SWT.COLOR_CYAN));
colors.add(display.getSystemColor(SWT.COLOR_GREEN));
colors.add(display.getSystemColor(SWT.COLOR_YELLOW));
colors.add(display.getSystemColor(SWT.COLOR_RED));
for (int i = 0; i < 5; i++)
{
Label label = new Label(shell, SWT.BORDER);
label.setText("Button " + i);
label.setBackground(colors.get(i));
labels.add(label);
}
Button sortButton = new Button(shell, SWT.TOGGLE);
sortButton.setText("Sort");
sortButton.addListener(SWT.Selection, new Listener()
{
@Override
public void handleEvent(Event e)
{
Button source = (Button) e.widget;
final boolean asc = source.getSelection();
Label oldFirst = labels.get(0);
Collections.sort(labels, new Comparator<Label>()
{
@Override
public int compare(Label o1, Label o2)
{
int result = o1.getText().compareTo(o2.getText());
if (asc)
result = -result;
return result;
}
});
Label label = labels.get(0);
label.moveAbove(oldFirst);
for (int i = 1; i < labels.size(); i++)
{
labels.get(i).moveBelow(labels.get(i - 1));
}
shell.layout();
}
});
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
开始后:
按下按钮后:
关于java - 重新排序 GridLayout SWT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19518767/