0

I tried to Find API that restrict component's movable area only in inside of Frame. Is there such API?

I guess such function is located in category of JFrame. but actually there are almost things about making components of Swing. I also searched API of SwingUtilities, but i think there are no useful API related to my problem.

public void mouseDragged(MouseEvent arg0) {
    // TODO Auto-generated method stub
    Point MousePoint=arg0.getPoint();
    label.setBounds(0, 0, c.getWidth(), c.getHeight());
    label.setLocation(MousePoint);
}
public void mouseReleased(MouseEvent e) {
    // TODO Auto-generated method stub
    label.setBounds(0, 0, c.getWidth(), c.getHeight());
    label.setLocation(getLocationOnScreen());
}

I expected using setBounds() will restrict movable area in Frame. but when i drag label over area of Frame, it was find that label move along.

2 Answers2

1

Usually you would add a ComponentListener to the label and implement the componentMoved method.

In that method you can then add checks, whether the component still is in bounds and set the location correspondingly:

label.addComponentListener(new ComponentAdapter() {
    @Override
    public void componentMoved(ComponentEvent e) {
        int newX = label.getX();
        int newY = label.getY();

        if(label.getX() < 0) {
            newX = 0;
        } else if(label.getX() + label.getWidth() > contentPane.getWidth()) {
            newX = contentPane.getWidth() - label.getWidth();
        }

        if(label.getY() < 0) {
            newY = 0;
        } else if(label.getY() + label.getHeight() > contentPane.getHeight()) {
            newY = contentPane.getHeight() - label.getHeight();
        }

        label.setLocation(newX, newY);
    }
});

This solution works fine for me!

LBPFR34K
  • 56
  • 1
  • 8
0

You can add simple if checks inside your mouseDragged and mouseReleased methods to keep the arguments for your setBounds/setLocation call inside a given range. You can use some example from Java - limit number between min and max to keep the numbers between 0 and "width/height of panel/canvas" like:

int ensureRange(int value, int min, int max) {
    return Math.min(Math.max(value, min), max);
}

You need to calculate the possible min and max values first. After that use these new values for the new bounds/location. The code might be looking like this (pseudo code):

public void mouseDragged(MouseEvent arg0) {
    Point mousePoint=arg0.getPoint();

    int x = ensureRange(mousePoint.x, 0, c.getWidth());
    int y = ensureRange(mousePoint.y, 0, c.getHeight());

    Point newPoint = new Point(x, y);

    label.setBounds(0, 0, c.getWidth(), c.getHeight());
    label.setLocation(newPoint);
}

You might need to adjust the limits based on your code.

Progman
  • 16,827
  • 6
  • 33
  • 48