-
问题内容:想做一个鼠标拖动控件的效果,应该怎么做。
- 原讨论链接:http://community.csdn.net/expert/topicview1.asp?id=5013666
- 所属论坛:GUI 设计
审核组:JAVA
- 提问者:dongle2001
解决者:mixianger
- 感谢:mq612 suooly mixianger
- 关键字:控件 Java 按钮 组件 new button public 鼠标 panel GUI 设计 松开 testdraged
- 答案:
依次建几个按钮,这样界面上就有一排按钮了。我想用户能够使用鼠标拖动其中的一个按钮到另外的某个按钮上,松开鼠标,这两个按钮的位置互换。可以做到吗?具体如何做,应该使用什么api,继承哪些事件。有代码最好。
---------------------------------------------------------------
两个按钮组件都需要监听鼠标
第一个组件当鼠标按下并拖动时,记录是哪个组件发生的事件,当鼠标进入第二个组件并松开时将两个组件的位置进行调整。
---------------------------------------------------------------
当然用到MoseListener和ActionListener拉...首先记录每个JButton的location.其中鼠标移动的时候可以记下getX()和getY(),拖动按钮时候如果和getX()跟getY相同那就隐藏一个按钮就行拉
---------------------------------------------------------------
让按钮跟着鼠标移动:
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);
}
});
}
}
- 评价:
给朵鲜花(5)
扔个鸡蛋(2)