Windowは、フレームやダイアログのスーパークラス。
通常はフレームやダイアログを使用するのでこのクラスを意識しなくてよいが、このクラスを利用してタイトルバーを持たない独自のウィンドウを作ることが出来る。
画像のみ(枠付き)を表示するウィンドウを作ってみた。
何に使うかというと、画像をマウスでドラッグするのを想定している。
画像というのも、特にコンポーネント(ボタンとかラベルとか)を想定している。つまり、画面上に配置されたコンポーネントをマウスでドラッグするときに使うイメージ。
public class ImageWindow extends Window {
protected Color borderColor = Color.BLACK;
protected Image image;
/**
* jre1.6で使用可能なコンストラクター
*/
public ImageWindow() {
super(null);
}
/**
* コンストラクター
*
* @param owner
*/
public ImageWindow(Window owner) {
super(owner);
}
Windowのコンストラクターには、親ウィンドウを指定してやる必要がある。存在しているウィンドウであれば、フレームでもダイアログでもよい。
jre1.6からは 親ウィンドウにnullを指定しても大丈夫なようになったようだが、jre1.5以前はnullを指定すると例外が発生する。
/** * 表示する画像をセット * * @param img 画像 */ public void setImage(Image img) { image = img; int w = img.getWidth(this); int h = img.getHeight(this); setSize(w, h); }
表示する画像をセットする初期化メソッド。
/** * 表示する画像を、現在表示されているコンポーネントから取得 * * @param c コンポーネント */ public void setImage(Component c) { try { Robot robot = new Robot(); Point pt = new Point(0, 0); SwingUtilities.convertPointToScreen(pt, c); Dimension sz = c.getSize(); setSize(sz); image = robot.createScreenCapture(new Rectangle(pt, sz)); } catch (AWTException e) { throw new RuntimeException(e); } }
画面に表示されているコンポーネントからImageを初期化するメソッド。
あくまで画面に表示されているものを取ってくるので、コンポーネントがウィンドウ外に出ている場合は その部分だけ妙な画像になる…。
public void setBorderColor(Color c) { borderColor = c; } public Color getBorderColor() { return borderColor; }
枠の色を指定・取得するメソッド。まぁオマケやね。
/** * 描画を行う * * @param g */ public void paint(Graphics g) { int w = getWidth(); int h = getHeight(); g.drawImage(image, 0, 0, null); //画像を描画 g.setColor(getBorderColor()); g.drawRect(0, 0, w-1, h-1); //枠線を描画 } }
マウスのクリックイベントで画像のドラッグを開始し、リリースイベント(ボタンを離した)でドラッグを終了する例。
Component c = new 〜; ←ラベルとかボタンとか
c.addMouseListener(new DragHandler());
class DragHandler implements MouseListener, MouseMotionListener {
private Point mouse_src, box_src;
private ImageWindow box = null;
/**
* ドラッグ開始
*/
public void mousePressed(MouseEvent e) {
Component c = (Component) e.getSource();
box = new ImageWindow(親ウィンドウ.this);
box.setImage(c);
mouse_src = e.getPoint();
Point pt = c.getLocation();
box_src = new Point(pt);
SwingUtilities.convertPointToScreen(pt, c.getParent());
box.setLocation(pt);
box.setVisible(true);
//box.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
e.consume();
}
/**
* ドラッグ中
*/
public void mouseDragged(MouseEvent e) {
if (box != null) {
Component c = (Component) e.getSource();
Point pt = e.getPoint();
pt.x += box_src.x - mouse_src.x;
pt.y += box_src.y - mouse_src.y;
SwingUtilities.convertPointToScreen(pt, c.getParent());
box.setLocation(pt);
e.consume();
}
}
/**
* ドラッグ終了
*/
public void mouseReleased(MouseEvent e) {
if (box != null) {
box.setVisible(false);
box.dispose();
box = null;
〜 //ボタンが離されたときの処理
e.consume();
}
}
〜
}
画像を表示するウィンドウを応用して、擬似的に背景が透過するドラッグ用のウィンドウを作ってみた。
→DragWindow [2007-02-25]