我正在写一个DnD程序来实现拖动功能。在调整框架大小之前,一切正常。 JLabel在面板内部没有任何问题。但是,当我尝试调整窗口大小时,JLabel会弹回原来的位置(幸运的是,DnD功能仍然可行)。如何防止JLabel回弹到原来的位置?它是否与重绘函数有关?(也许我必须重写函数?)这是我的JFrame构造函数的代码:
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
getContentPane().setLayout(new BorderLayout(0, 0));
textField = new JTextField();
getContentPane().add(textField, BorderLayout.NORTH);
textField.setColumns(10);
MainPanel = new JPanel();
getContentPane().add(MainPanel, BorderLayout.CENTER);
MainPanel.setLayout(new GridLayout(1, 0, 0, 0));
Left_Panel = new JPanel();
Left_Panel.setTransferHandler(new DragAndDropTransferHandler());
Left_Panel.setDropTarget(new DropTarget(MainFrame.this, new MyDropTargetListener(this)));
Left_Panel.setBorder(new TitledBorder("Panel 1"));
MyLabel ML = new MyLabel();
ML.setBounds(50 , 70, 61, 16);
Left_Panel.add(ML);
MainPanel.add(Left_Panel);
Right_Panel = new JPanel();
Right_Panel.setBounds(201, 0, 200, 400);
Right_Panel.setTransferHandler(new DragAndDropTransferHandler());
Right_Panel.setDropTarget(new DropTarget(MainFrame.this, new MyDropTargetListener(this)));
Right_Panel.setBorder(new TitledBorder("Panel 2"));
MainPanel.add(Right_Panel);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
这是我的目标侦听器的drop函数。
@Override
public void drop(DropTargetDropEvent dtde) {
DataFlavor dragAndDropPanelFlavor = null;
Object transferableObj = null;
Transferable transferable = null;
try {
dragAndDropPanelFlavor = MainFrame.getFlavor();
transferable = dtde.getTransferable();
dtde.getDropTargetContext();
// What does the Transferable support
if (transferable.isDataFlavorSupported(dragAndDropPanelFlavor)) {
transferableObj = dtde.getTransferable().getTransferData(dragAndDropPanelFlavor);
}
} catch (Exception ex) {
System.out.println("Error");
}
if (transferableObj == null) return;
if (transferableObj instanceof MyLabel) {
MyLabel ML = (MyLabel) transferableObj;
ML.setBounds(dtde.getLocation().x, dtde.getLocation().y, 61, 16);
}
}
我目前只在左侧面板上工作。告诉我是否需要提供更多代码。