第 1 頁:單選題 |
第 5 頁:操作題 |
第 7 頁:參考答案 |
四、綜合應(yīng)用題(共18分)
本題的功能是監(jiān)聽鼠標的操作。鼠標置于窗口中單擊時(左鍵或右鍵),在單擊的地方會畫一個小矩形,如果將鼠標置于小矩形上,則鼠標光標狀態(tài)改為小十字,按下鼠標左鍵可拖曳,雙擊鼠標左鍵(或右鍵)時,小矩形消失。
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.geom.*;
import javax.swing.*;
public class java3
{
public static void main(String[]args)
{
MouseFrame frame=new MouseFrame():
frame.setDefaultCloseOperation(JFrame.EXIT_
oN_CLOSE);
frame.show();
}
}
class MouseFrame extends JFrame
{
public MouseFrame()
{
setTitle("java3");
setSize(DEFAULT WIDTH, DEFAULT
HEIGHT):
MousePanel panel=new MousePanel();
Container contentPane=getContentPane();
contentPane.add(panel);
}
public static final int DEFAULT_WIDTH=300;
public static final int DEFAULT_HEIGHT=200;
}
class MousePanel extends JPanel
{
public MousePanel()
{
squares=new ArrayList();
current=null:
addMouseListener(new MouseHandler());
addMouseMotionListener(new MouseMotionHan-
dler());
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2=(Graphics2D)g;
for(int i=0;i g2.draw((Rectangle2D)squares.get(i));
}
public void find(Point2D p)
{
for(int i=0;i {
Rectangle2D r=(Rectangle2D)squares.get(i);
if(r.contains(p))return r;
}
return null:
}
public void add(Point2D p)
{
double x=P.getX();
double Y=P.getY():
current=new Rectangle2D.Double(
x-SIDELENGTH/2.
y-SlDELENGTH/2.
S1DELENGTH,
SIDELENGTH);
squares.add(current);
repaint();
}
public void remove(Rectangle2D s)
{
if(S= =null)return:
if(S= =current)current=null;
squares.remove(s):
repaint();
}
private static final int SIDELENGTH=10:
private ArrayList squares;
private Rectangle2D current;
private class MouseHandter extends MouseAction-
Listener
{
public void mousePressed(MouseEvent event)
{
current=find(event.getPoint());
if(current= =null)
add(event.getPoint());
}
public void mouseClicked(MouseEvent event)
{
current=find(event.getPoint());
if(current!=null&&event.getClickCount()
>=2)
remove(current);
}
}
private class MouseMotionHandler implements Mouse-
MotionListener
{
public void mouseMoved(MouseEvent event)
{
if(find(event.getPoint)= =null)
setCursor(Cursor.getDefaultCursor());
else
setCursor(Cursor.getPredefinedCursor
(Cursor.CROSSHAIR_CURSOR));
}
public void mouseDragged(MouseEvent event)
{
if(current!=null)
{
int x=event.getX():
int Y=event.getY(); 、
current.setFrame(
x-SIDELENGTH/2,
Y-SlDELENGTH/2.
SIDELENGTH,
SIDELENGTH);
repaint();
}
}
}
}
相關(guān)推薦:
北京 | 天津 | 上海 | 江蘇 | 山東 |
安徽 | 浙江 | 江西 | 福建 | 深圳 |
廣東 | 河北 | 湖南 | 廣西 | 河南 |
海南 | 湖北 | 四川 | 重慶 | 云南 |
貴州 | 西藏 | 新疆 | 陜西 | 山西 |
寧夏 | 甘肅 | 青海 | 遼寧 | 吉林 |
黑龍江 | 內(nèi)蒙古 |