我希望在运行时通过单击其边框并拖动它来调整JButton
的大小。任何人都可以用示例代码向我解释如何使用它。
public void mouseDragged(MouseEvent E)
{
Point point= E.getPoint();
//JButton get = floor_plan.dynamicButtons.get(E.getComponent());
JButton get=(JButton) E.getComponent();
int height = get.getHeight();
int width = get.getWidth();
int X=E.getXOnScreen();
int Y=E.getYOnScreen();
if(floor_plan.resize==1)
if (floor_plan.isHeld) {
System.out.println(X);
System.out.println(Y);
get.setPreferredSize(
new Dimension(floor_plan.grabbedDimension.width -
(floor_plan.grabbedPoint.x - point.x),
floor_plan.grabbedDimension.height -
(floor_plan.grabbedPoint.y - point.y)));
get.setBounds(new Rectangle(get.getLocation(), get.getPreferredSize()));
return;
}
System.out.println("height:"+height);
System.out.println("width:"+width);
get.setBounds(X-240,Y-125,height,width);
}
答案 0 :(得分:2)
答案 1 :(得分:2)
嗯,这可能会为你做。添加新按钮时,只需添加ResizableButton
即可。
请注意,无论您点击它的位置,它都会调整大小。
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;
}
});
}
}
答案 2 :(得分:0)