2012-07-12 43 views
2

所以我一直在尋找這個以外的JLabel:dragging a jlabel around the screen拖動一個JFrame

有沒有辦法拖一個JLabel(或一個的表示)一個JFrame之外?

例如拖動一個JLabel JFrames之間,而實際上是 「表示」 選擇JLabel被拖動(使用http://docs.oracle.com/javase/tutorial/uiswing/dnd/intro.html

+0

你沒有回答你自己的問題嗎? – 2012-07-12 16:30:41

+0

我是如何回答自己的問題的? – systemoutprintln 2012-07-12 18:21:19

回答

3

使用的JWindow測試:

//http://stackoverflow.com/questions/4893265/dragging-a-jlabel-around-the-screen 
private final JWindow window = new JWindow(); 
@Override 
public void mouseDragged(MouseEvent me) { 
    if (dragLabel == null) { 
     return; 
    } 
    int x = me.getPoint().x - dragLabelWidthDiv2; 
    int y = me.getPoint().y - dragLabelHeightDiv2; 
    //dragLabel.setLocation(x, y); 
    window.add(dragLabel); 
    window.pack(); 
    Point pt = new Point(x, y); 
    Component c = (Component)me.getSource(); 
    SwingUtilities.convertPointToScreen(pt, c); 
    window.setLocation(pt); 
    window.setVisible(true); 
    repaint(); 
} 
@Override public void mouseReleased(MouseEvent me) { 
    window.setVisible(false); 
    //... 
} 

下面是未測試的代碼: (可能需要一些按摩的工作,但是這是它的要點)

@Override public int getSourceActions(JComponent src) { 
    JLabel label = (JLabel)src; 
    window.add(label); 
    window.pack(); 
    window.setVisible(true); 
    return MOVE; 
} 
//... 
DragSource.getDefaultDragSource().addDragSourceMotionListener(new DragSourceMotionListener() { 
    @Override public void dragMouseMoved(DragSourceDragEvent dsde) { 
    Point pt = dsde.getLocation(); 
    pt.translate(5, 5); // offset 
    window.setLocation(pt); 
    } 
});