class MyWindow extends JComponent implements MouseListener,
MouseMotionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
public static final int TYPE_NORTH = 0;
public static final int TYPE_SOUTH = 2;
private int type;
private Point pointPressed;
private Point pointReleased;
public static MyWindow setPane(JFrame frame, int type) {
MyWindow dragger = new MyWindow(frame, type);
Container pane = frame.getContentPane();
if (type == TYPE_NORTH) {
pane.add(dragger, BorderLayout.NORTH);
} else if (type == TYPE_SOUTH) {
pane.add(dragger, BorderLayout.SOUTH);
}
return dragger;
}
public MyWindow(JFrame frame, int type) {
this.frame = frame;
this.type = type;
setBackground(Color.red);
setOpaque(true);
setUI(new ComponentUI() {
});
setPreferredSize(new Dimension(5, 5));
addMouseListener(this);
addMouseMotionListener(this);
}
public void mousePressed(MouseEvent e) {
pointPressed = e.getLocationOnScreen();
updateCursor(true);
}
private void updateCursor(boolean on) {
if (on) {
if (type == TYPE_NORTH) {
setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
} else if (type == TYPE_SOUTH) {
setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR));
}
} else {
setCursor(null);
}
}
public void mouseReleased(MouseEvent e) {
pointReleased = e.getLocationOnScreen();
int deltaY = pointReleased.y - pointPressed.y;
Point location = frame.getLocation();
Dimension size = frame.getSize();
Dimension minSize = frame.getMinimumSize();
if (type == TYPE_NORTH) {
size.height -= deltaY;
if(minSize.height < size.height)
location.y += deltaY;
} else if (type == TYPE_SOUTH) {
size.height += deltaY;
}
if (minSize != null) {
if (size.width < minSize.width) {
size.width = minSize.width;
}
if (size.height < minSize.height) {
size.height = minSize.height;
}
}
frame.setBounds(location.x, location.y, size.width, size.height);
Rectangle r = new Rectangle(getLocationOnScreen(), getSize());
updateCursor(r.contains(pointReleased));
pointPressed = null;
pointReleased = null;
}
public void mouseDragged(MouseEvent e) {
mouseReleased(e);
pointPressed = e.getLocationOnScreen();
}
public void mouseMoved(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
updateCursor(true);
}
public void mouseClicked(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}