2010年8月17日 星期二

Java 視窗滑鼠事件實作

在任何視窗程式中,都會有很多關於滑鼠的 Event

譬如:按下或放開滑鼠左鍵、右鍵,或是移入某特定區之類的

以下的程式主要是以一個視窗為底

那當使用者滑鼠移入視窗內時會把始窗的背景色換成黃色

並且在左上方顯示進入視窗的位置

如果在視窗內按下滑鼠左或右鍵 會在點擊處印出 DOWN

放開則會在事件發生處印出 UP

當移出視窗時則會將被景色換成白色

並顯示於哪個位置移出

以上都會實作到很多有關滑鼠的事件

大家可以練習看看,程式如下:


import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class MouseTest extends JFrame
{
JLabel lbl;
public static void main(String[] args)
{
MouseTest app = new MouseTest();
app.setSize(300,300);
app.setVisible(true);
}
public MouseTest()
{
final Container c = getContentPane();
c.setBackground(Color.white);
lbl = new JLabel(); //視窗左上方的 Label

addMouseListener(new MouseAdapter(){
public void mouseEntered(MouseEvent e){ //當滑鼠游標進入物件範圍
int x = e.getX(); //擷取發生事件的 X 座標
int y = e.getY(); //擷取發生事件的 Y 座標
c.setBackground(Color.yellow);
lbl.setText("Mouse is moving to" + Integer.toString(x) + "," + Integer.toString(y));
}
});
addMouseListener(new MouseAdapter(){
public void mouseExited(MouseEvent e){ //當滑鼠游標進入物件範圍
int x = e.getX();
int y = e.getY();
c.setBackground(Color.white);
lbl.setText("Mouse just left the window from" + Integer.toString(x) + "," + Integer.toString(y));
}
});
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){ //實做滑鼠的點擊事件
Graphics g = getGraphics();
int x = e.getX();
int y = e.getY();
g.drawString("DOWN",x,y); //在事件發生的座標繪上 "DOWN" 字樣
lbl.setText("Mouse is pressed at" + Integer.toString(x) + "," + Integer.toString(y));
}
});
addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){ //實做滑鼠的放開事件
Graphics g = getGraphics();
int x = e.getX();
int y = e.getY();
g.drawString("UP",x,y);
lbl.setText("Mouse is released from" + Integer.toString(x) + "," + Integer.toString(y));
}
});
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){ //實做滑鼠的拖曳事件
Graphics g = getGraphics();
int x = e.getX();
int y = e.getY();
g.drawString("Dragging",x,y);
lbl.setText("Mouse is Dragging at" + Integer.toString(x) + "," + Integer.toString(y));
}
});
c.add(lbl,BorderLayout.NORTH);
}
}

1 則留言: