在Jframe中移动对象

时间:2015-05-14 01:29:31

标签: java swing listener mouselistener

我有一些我想要移动的JButton,例如在这段代码中:

package javaapplication19;
import java.awt.*;
import java.awt.Container;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;


public class JavaApplication19 extends JFrame{
    public static JButton button=new JButton("Button");//Button to move
    public static int x;
    public static int y;
    public JavaApplication19(){
        final Container C = getContentPane();
        C.setLayout(null);
        button.setBounds(100,100,100,100);
        C.add(button);
        //MouseListenerStart
    button.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    if(!e.isMetaDown()){
    x = e.getX();
    y = e.getY();
    }
    }
    });
    button.addMouseMotionListener(new MouseMotionAdapter() {
    public void mouseDragged(MouseEvent e) {
    if(!e.isMetaDown()){
    Point p = getLocation();
    button.setLocation(p.x + e.getX() - x,
    p.y + e.getY() - y);
    }
    }
    });
//MouseListenerend
    }
    public static void main(String[] args) {
        JavaApplication19 marco=new JavaApplication19 ();
        marco.setSize(1000,700);
        marco.setVisible(true);
        marco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
    }}

但有两个问题。第一个是JButton比鼠标移动得慢。第二个是当拖动它时,JButton似乎在JFrame中的两个位置之间跳转。

我怎样才能解决这些问题?

2 个答案:

答案 0 :(得分:0)

解决。

在此代码中:

package javaapplication19;
import java.awt.*;
import java.awt.Container;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;


public class JavaApplication19 extends JFrame{
    public static JButton button=new JButton("Button");//Button to move
    public static int x;
    public static int y;
    public JavaApplication19(){
        final Container C = getContentPane();
        C.setLayout(null);
        button.setBounds(100,100,100,100);
        C.add(button);
        //MouseListenerStart
    button.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    if(!e.isMetaDown()){
    x = e.getX();
    y = e.getY();
    }
    }
    });
    button.addMouseMotionListener(new MouseMotionAdapter() {
    public void mouseDragged(MouseEvent e) {
    if(!e.isMetaDown()){
    Point p = button.getLocation();\\I Simply had to put button.getLocation() instead of getLocation()
    button.setLocation(p.x + e.getX() - x,
    p.y + e.getY() - y);
    }
    }
    });
//MouseListenerend
    }
    public static void main(String[] args) {
        JavaApplication19 marco=new JavaApplication19 ();
        marco.setSize(1000,700);
        marco.setVisible(true);
        marco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
    }
}

答案 1 :(得分:0)

您应该尝试编写可用于任何组件的更通用的代码。您在解决方案中发布的代码是硬编码的,因此它只适用于名为“button”的变量。

对于允许您拖动任何组件的更通用的解决方案,请查看Moving Windows中的Basic Dragging部分。