在panel上用滑鼠拖曳button

import javax.swing.*;
import java.awt.*;

import java.awt.event.*;
import java.awt.image.ImageObserver;
import java.util.Vector;
import java.net.URL;

public class ButtonMove extends JFrame {

    JButton jButton1 = new JButton();
    int focusx = 0;
    int focusy = 0;

    public ButtonMove() {
        try {
            jbInit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void jbInit() throws Exception {
        jButton1.setBounds(new Rectangle(86, 113, 73, 25));
        jButton1.setText("jButton1");
        jButton1.addMouseListener(new MouseProcess() {
        });
        jButton1.addMouseMotionListener(new MouseMotionProcess());

        this.setLocale(java.util.Locale.getDefault());
        this.getContentPane().setLayout(null);
        this.getContentPane().add(jButton1, null);
        this.setSize(400, 500);
        this.setVisible(true);
    }

    private class MouseProcess extends MouseAdapter {

        public void mouseClicked(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
            focusx = e.getX();
            focusy = e.getY();


        }
    }

    private class MouseMotionProcess extends MouseMotionAdapter {

        public void mouseDragged(MouseEvent e) {
            Container container = jButton1.getParent();
            int w = container.getWidth();
            int h = container.getHeight();

            int x = jButton1.getX() + e.getX() - focusx;
            int y = jButton1.getY() + e.getY() - focusy;

            if (x + jButton1.getWidth() > w) {
                x = w - jButton1.getWidth();
            }
            if (y + jButton1.getHeight() > h) {
                y = h - jButton1.getHeight();
            }
            if (x < 0) {
                x = 0;
            }
            if (y < 0) {
                y = 0;
            }

            jButton1.setLocation(x, y);
            //jButton1.setLocation(x, y + jButton1.getHeight());
            container.repaint();
            container = null;
        }
    }

    public static void main(String args[]) {
        new ButtonMove();
    }
}

你可能感兴趣的:(java,.net,swing)