I want to be able to make collisions for drag components in Java Swing - Stack Overflow

admin2025-04-29  1

I tried making a JPanel component become draggable off a YT vid I watched, the problem with it is that it drags the panel even if my mouse is not directly over it. I also tried looking online to see how to set bounds for the dragging, but I couldn't find anything on it. I was wondering if anyone had the solution.

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

public class DragPanel extends JPanel {

    ImageIcon image = new ImageIcon("A:\\Aseprite\\Saves\\Blue Log.png");
    Point imageCorner;
    Point prePt;

    DragPanel() {

        imageCorner = new Point(0,0);
        ClickListener clickListener = new ClickListener();
        DragListener dragListener = new DragListener();
        this.addMouseListener(clickListener);
        this.addMouseMotionListener(dragListener);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        image.paintIcon(this, g,(int)imageCorner.getX(),(int)imageCorner.getY());
    }

    private class ClickListener extends MouseAdapter {

        public void mousePressed(MouseEvent e) {
            prePt = e.getPoint();
        }
    }

    private class DragListener extends MouseMotionAdapter {

        public void mouseDragged(MouseEvent e) {
            Point currentPt = e.getPoint();

            imageCorner.translate(((int)(currentPt.getX() - prePt.getX())), (int)(currentPt.getY() - prePt.getY()));
            prePt = currentPt;
            repaint();
        }
    }
}

I tried making a JPanel component become draggable off a YT vid I watched, the problem with it is that it drags the panel even if my mouse is not directly over it. I also tried looking online to see how to set bounds for the dragging, but I couldn't find anything on it. I was wondering if anyone had the solution.

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

public class DragPanel extends JPanel {

    ImageIcon image = new ImageIcon("A:\\Aseprite\\Saves\\Blue Log.png");
    Point imageCorner;
    Point prePt;

    DragPanel() {

        imageCorner = new Point(0,0);
        ClickListener clickListener = new ClickListener();
        DragListener dragListener = new DragListener();
        this.addMouseListener(clickListener);
        this.addMouseMotionListener(dragListener);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        image.paintIcon(this, g,(int)imageCorner.getX(),(int)imageCorner.getY());
    }

    private class ClickListener extends MouseAdapter {

        public void mousePressed(MouseEvent e) {
            prePt = e.getPoint();
        }
    }

    private class DragListener extends MouseMotionAdapter {

        public void mouseDragged(MouseEvent e) {
            Point currentPt = e.getPoint();

            imageCorner.translate(((int)(currentPt.getX() - prePt.getX())), (int)(currentPt.getY() - prePt.getY()));
            prePt = currentPt;
            repaint();
        }
    }
}

Share Improve this question asked Jan 7 at 4:10 CalmentCalment 111 bronze badge 1
  • Hello Calment, welcome, when you assign imageCorner its “x” and “y” values, you must verify that they do not go out of range, that is, “x” cannot be less than “0” and “x” plus the width of the image, cannot be greater than the width of the panel, the same for “y”. – Marce Puente Commented Jan 7 at 9:13
Add a comment  | 

1 Answer 1

Reset to default 0

Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.

The code posted in the question creates a JPanel. In order to make the code runnable, I added some code.

Here's an image of the GUI I created.

I found an image on the Internet. I added a JFrame to hold the JPanel.

The mousePressed method was modified to check if the pressed point was within the bounds of the image. The mouseDragged method was modified to check if the pressed point was valid or not.

Here's the complete runnable code.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class DragPanelExample implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new DragPanelExample());
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("DragPanel Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(new DragPanel(), BorderLayout.CENTER);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public class DragPanel extends JPanel {

        private static final long serialVersionUID = 1L;

        ImageIcon image;
        Point imageCorner;
        Point prePt;

        public DragPanel() {
            this.imageCorner = new Point(0, 0);
            this.image = getImage("https://www.wallpaperflare.com/static/"
                    + "454/537/313/wood-texture-blue-tree-wallpaper.jpg");
            this.setPreferredSize(new Dimension(960, 540));

            ClickListener clickListener = new ClickListener();
            DragListener dragListener = new DragListener();
            this.addMouseListener(clickListener);
            this.addMouseMotionListener(dragListener);
        }

        private ImageIcon getImage(String urlString) {
            try {
                @SuppressWarnings("deprecation")
                URL url = new URL(urlString);
                Image image = ImageIO.read(url);
                Image smallImage = image.getScaledInstance(192, 108,
                        Image.SCALE_SMOOTH);
                return new ImageIcon(smallImage);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            image.paintIcon(this, g, (int) imageCorner.getX(),
                    (int) imageCorner.getY());
        }

        private class ClickListener extends MouseAdapter {

            @Override
            public void mousePressed(MouseEvent e) {
                Point currentPt = e.getPoint();
                if (currentPt.x <= (imageCorner.x + image.getIconWidth())
                        && (currentPt.x >= imageCorner.x)
                        && (currentPt.y <= (imageCorner.y + image.getIconHeight()))
                        && (currentPt.y >= imageCorner.y)) {
                    prePt = e.getPoint();
                } else {
                    prePt = null;
                }
                
            }
        }

        private class DragListener extends MouseMotionAdapter {

            @Override
            public void mouseDragged(MouseEvent e) {
                if (prePt != null) {
                    Point currentPt = e.getPoint();
                    imageCorner.translate(
                            ((int) (currentPt.getX() - prePt.getX())),
                            (int) (currentPt.getY() - prePt.getY()));
                    prePt = currentPt;
                    repaint();
                }
            }
        }
    }

}
转载请注明原文地址:http://anycun.com/QandA/1745932748a91307.html