Well, this might do it for you. When adding the new button, simply add a ResizableButton
instead.
Note, it will resize no matter where you click on it.
public class ResizableButton extends JButton {
private Point grabbedPoint;
private Dimension grabbedDimension;
private boolean isHeld = false;
public ResizableButton(String name) {
super(name);
addMouseListener(clickListener);
addMouseMotionListener(moveListener);
}
private MouseMotionListener moveListener = new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if (isHeld) {
Point newP = e.getPoint();
setPreferredSize(new Dimension(grabbedDimension.width
- (grabbedPoint.x - newP.x), grabbedDimension.height
- (grabbedPoint.y - newP.y)));
setBounds(new Rectangle(getLocation(), ResizableButton.this
.getPreferredSize()));
}
}
};
private MouseListener clickListener = new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
isHeld = false;
}
@Override
public void mousePressed(MouseEvent e) {
isHeld = true;
grabbedPoint = e.getPoint();
grabbedDimension = ((JButton) e.getSource()).getSize();
}
};
}
Below is code for a button that moves or re-sizes based on whether or not the Alt button is pressed.:
public class MovableResizableButton extends JButton {
private boolean isHeld;
private Point pointClicked;
private Dimension startingSize;
public MovableResizableButton(String name) {
super(name);
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if (isHeld) {
Dimension newSize = getPreferredSize();
Point newPoint = getLocation();
if ((e.getModifiersEx() & InputEvent.ALT_DOWN_MASK) == InputEvent.ALT_DOWN_MASK) {
newSize = new Dimension(startingSize.width - (pointClicked.x - e.getPoint().x),
startingSize.height -(pointClicked.y - e.getPoint().y));
}else {
Point startPoint = getLocation();
newPoint = new Point(startPoint.x - (pointClicked.x - e.getPoint().x),
startPoint.y - (pointClicked.y - e.getPoint().y));
}
setPreferredSize(newSize);
setBounds(new Rectangle(newPoint, getPreferredSize()));
}
}
});
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
pointClicked = e.getPoint();
startingSize = getSize();
isHeld = true;
}
@Override
public void mouseReleased(MouseEvent e) {
isHeld = false;
}
});
}
}