まあ、これはあなたのためにそれを行うかもしれません。新しいボタンを追加するときは、ResizableButton
代わりに a を追加するだけです。
どこをクリックしてもサイズが変更されることに注意してください。
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();
}
};
}
Alt以下は、ボタンが押されたかどうかに基づいて移動またはサイズ変更するボタンのコードです。
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;
}
});
}
}