依次建几个按钮,这样界面上就有一排按钮了。我想用户能够使用鼠标拖动其中的一个按钮到另外的某个按钮上,松开鼠标,这两个按钮的位置互换。可以做到吗?具体如何做,应该使用什么api,继承哪些事件。有代码最好。

解决方案 »

  1.   

    当然用到MoseListener和ActionListener拉...首先记录每个JButton的location.其中鼠标移动的时候可以记下getX()和getY(),拖动按钮时候如果和getX()跟getY相同那就隐藏一个按钮就行拉
      

  2.   

    让按钮跟着鼠标移动:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;public class TestDraged extends JFrame 
    {
    public Button button;
    Panel panel;
    static Point origin = new Point();
    int x=0;
    int y=0;

    public TestDraged()
    {
    super("TestMouseDragged");
    this.setSize(600,400);
    button=new Button("Test MouseDragged");
    panel=new Panel();
    panel.add(button);
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add("Center",panel);

    button.addMouseListener(new MouseAdapter() 
    {
                public void mousePressed(MouseEvent e) 
                {
                    origin.x = e.getX();
                    origin.y = e.getY();
                }
            });
    button.addMouseMotionListener(new MouseMotionAdapter()
    {
    public void mouseDragged(MouseEvent e)
            {
            Point p = button.getLocation();
            button.setLocation(p.x + e.getX() - origin.x, p.y + e.getY()
    - origin.y);
             repaint();
            }
    });
    }

    public static void main(String args[])
    {
    TestDraged app=new TestDraged();
    app.setVisible(true);
    app.addWindowListener(new WindowAdapter()
    {
    public void windowClosing(WindowEvent e)
    {
    System.exit(0);
    }
    });
    }
    }
      

  3.   

    发现一个问题,当拖拽一个按钮的时候,另一个按钮不能得到鼠标消息。只能判断鼠标位置是否在另一个按钮范围内。不过有个问题,如何得到按钮的范围。我现在只能得到按钮的位置,也就是left和top。如何得到它的width和height?
      

  4.   

    通过drop接口可以判断是否释放到某个button上,应该不需要判断光标位置吧。
      

  5.   

    通过drop接口可以判断是否释放到某个button上,应该不需要判断光标位置吧。
    不行,同一时刻,只能有一个按钮捕获鼠标