我一直在尝试使用拖放来允许用户重新排列显示的某些容器的顺序。因为屏幕需要滚动,所以我使用了按钮的长按监听器将容器设置为可拖动。来自其他问题的建议表明,添加 form.pointerPressed(x, y) 然后添加 pointerDragged 允许拖动在长按时启动,效果很好。到目前为止,一切都很好。下面的代码和图像以绿色显示主容器,以蓝色显示所有其他组件。
Form formDnD = new Form("拖放", new BorderLayout()); formDnD.getToolbar().setBackCommand("", e -> mainForm.showBack());
Container northcnt = new Container(new BoxLayout(BoxLayout.Y_AXIS));
Container centercnt = new Container(new BoxLayout(BoxLayout.Y_AXIS));
centercnt.setScrollableY(true);
centercnt.setDropTarget(true);
Container southcnt = new Container(new BoxLayout(BoxLayout.Y_AXIS));
Style a = UIManager.getInstance().getComponentStyle("Icon");
FontImage iconDnD = FontImage.createMaterial(FontImage.MATERIAL_DRAG_HANDLE, a, 6);
for(int i = 0; i <= 5; i++){
Container c_Master = new Container(new BoxLayout(BoxLayout.Y_AXIS));
c_Master.setUIID("GreenCont");
Container c = new Container(new BoxLayout(BoxLayout.Y_AXIS));
c.setUIID("MyButtonBlue");
c_Master.add(c);
Button b1 = new Button();
b1.setUIID("Icon");
b1.setIcon(iconDnD);
c.add(new Label("Label 1"));
c.add(b1);
c.add(new Label("Label 2"));
c.add(new Label("Label 3"));
b1.addLongPressListener(actionEvent -> {
c_Master.setDraggable(true);
int x = actionEvent.getX();
int y = actionEvent.getY();
formDnD.pointerPressed(x, y);
c_Master.pointerDragged(x, y);
});
c_Master.addDropListener(actionEvent -> {
if(c_Master.isDraggable()) {
c_Master.setDraggable(false);
}
});
centercnt.add(c_Master);
}
formDnD.add(BorderLayout.NORTH, northcnt).add(BorderLayout.CENTER, centercnt).add(BorderLayout.SOUTH, southcnt);
formDnD.show();
如果用户在绿色区域释放容器,则容器会落在该位置。如果用户将容器放在蓝色区域的任何位置,则不会掉落任何东西。我如何实现这一目标?
在你的例子中,我认为
c_Master
需要成为放置目标,因为在这种特殊情况下你会把组件放在那里。