Swing/MouseInfo のバックアップの現在との差分(No.12)
- category: swing folder: MouseInfo title: Screen上にあるMouseの位置を取得する tags: [MouseInfo, Timer] author: aterai pubdate: 2007-10-29T13:39:49+09:00 description: Screen上にあるMouseの絶対位置を取得して、パネル内のラケットを移動します。 image:
概要
Screen
上にあるMouse
の絶対位置を取得して、パネル内のラケットを移動します。
Screenshot
Advertisement
サンプルコード
public static final Dimension panelDim = new Dimension(320, 240);
private final Racket racket = new Racket(panelDim);
#spanadd
#spanend
public MainPanel() {
super(new BorderLayout());
setPreferredSize(panelDim);
new javax.swing.Timer(10, this).start();
new Timer(10, this).start();
}
#spanadd
#spanend
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
racket.draw(g);
}
#spanadd
#spanend
@Override public void actionPerformed(ActionEvent e) {
PointerInfo pi = MouseInfo.getPointerInfo();
Point pt = pi.getLocation();
SwingUtilities.convertPointFromScreen(pt, this);
racket.move(pt.x);
repaint();
}
View in GitHub: Java, Kotlin解説
上記のサンプルでは、マウスカーソルがパネル外に移動した場合でもラケットを動かせるように、以下のような方法を使用しています。
Timer
を使用して10
ミリ秒ごとにMouseInfo
からPointerInfo
を取得PointerInfo
から画面上でのポインタ座標を取得-
SwingUtilities.convertPointFromScreen(...)
メソッドで、これをパネル相対の座標に変換 -
SwingUtilities.convertPointFromScreen(...)
メソッドでこれをパネル相対の座標に変換 - ラケットに変換した座標を与えて
JPanel#repaint()
メソッドで再描画