TITLE:JComponentの移動、リサイズ
#navi(../)
*JComponentの移動、リサイズ [#v450b08b]
Posted by [[terai]] at 2008-05-19

#contents

**概要 [#af02f69f]
JLayeredPaneに、移動、リサイズ可なコンポーネントを追加します。

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#n84bb09d]
#code{{
public void mouseDragged(MouseEvent e) {
  if(startPos==null || startingBounds==null) return;
  Point p = SwingUtilities.convertPoint((Component)e.getSource(), e.getX(), e.getY(), null);
  int deltaX = startPos.x - p.x;
  int deltaY = startPos.y - p.y;
  int newX = getX();
  int newY = getY();
  int newW = getWidth();
  int newH = getHeight();

  JComponent parent = (JComponent)getParent();
  Rectangle parentBounds = parent.getBounds();
  Dimension min = new Dimension(50,50);
  Dimension max = new Dimension(500,500);

  switch(cursor) {
    case Cursor.N_RESIZE_CURSOR: {
      if(startingBounds.height + deltaY < min.height) {
        deltaY = -(startingBounds.height - min.height);
      }else if(startingBounds.height + deltaY > max.height) {
        deltaY = max.height - startingBounds.height;
      }
      if(startingBounds.y - deltaY < 0) { deltaY = startingBounds.y; }
      newX = startingBounds.x;
      newY = startingBounds.y - deltaY;
      newW = startingBounds.width;
      newH = startingBounds.height + deltaY;
      break;
    }
    case Cursor.NE_RESIZE_CURSOR: {
      if(startingBounds.height + deltaY < min.height) {
        deltaY = -(startingBounds.height - min.height);
//......
}}

**解説 [#sc16de97]
上記のサンプルでは、ツールバーやポップアップメニューから、移動、リサイズ可能なJTableやJTreeを追加することができます。

リサイズボーダーの描画などは、[[Resizable Components - Santhosh Kumar's Weblog>http://www.jroller.com/santhosh/entry/resizable_components]]から、マウスのドラッグによる移動、リサイズの最大値、最小値の制限などは、%JAVA_HOME%/src/javax/swing/plaf/basic/BasicInternalFrameUI.java からの引用です。

----
JDK1.5では、JLayeredPane#setComponentPopupMenuを使う場合、以下のようにダミーのマウスリスナーなどを追加しておく必要があります。
#code{{
layer.setComponentPopupMenu(new MyPopupMenu());
layer.addMouseListener(new MouseAdapter() {});
}}

**参考リンク [#qf2f4f0c]
-[[Resizable Components - Santhosh Kumar's Weblog>http://www.jroller.com/santhosh/entry/resizable_components]]

**コメント [#r6bdc669]
#comment