import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.awt.geom.*;
public class MouseTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
MouseFrame frame = new MouseFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class MouseFrame extends JFrame
{
public MouseFrame()
{
setTitle("MouseTest");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
MouseComponent component = new MouseComponent();
add(component);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}
class MouseComponent extends JComponent
{
public MouseComponent()
{
squares = new ArrayList<Rectangle2D>();
current = null;
addMouseListener(new MouseHandler());
addMouseMotionListener(new MouseMotionHandler());
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
for(Rectangle2D r:squares)
{
g2.draw(r);
}
}
public Rectangle2D find(Point2D p)
{
for(Rectangle2D r:squares)
{
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-SIDELENGTH/2, SIDELENGTH, 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<Rectangle2D> squares;
private Rectangle2D current;
private class MouseHandler extends MouseAdapter
{
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 MouseMotionListener
{
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-SIDELENGTH/2, SIDELENGTH, SIDELENGTH);
repaint();
}
}
}
}
1.结合鼠标事件和swing 2D图形技术的简单运用,可以利用鼠标的单击或双击完成相应操作 。
简单功能为,单击鼠标就可以在窗口上出现一个小正方形,双击即可删除,按住可以拖动。
PS:可以利用这些悄悄的写下你心爱的人的名字哦~~虽然字看起来歪歪斜斜的,不过证明心意嘛~~嘿嘿
2.浮点数在内存中的表示方式
这个要认真理解,我花了将近一个小时的时间
首先是在JDK中了解Float中的intBitsToFloat方法的含义。
s * m * 2^(e-150)
s为符号位,int s = ((bits & 31 ) == 0)? 1:-1 0表示为正。
e表示存储在内存中的23位到31位bits,作为幂指数。 int e =(bits>> 23)& 0xff
m表示存储在内存中的0到22位bits,作为有效位。 int m = (e == 0)? (bits & 0x7fffff) << 1 : (bits & 0x7fffff) | 0x800000;
例如,计算0x50000000的对应的浮点数
s=0;
e 后23位有效位与0xff相与之后结果为 10100000 结果为160
m 与 0x800000相或后结果为2^23
所以结果为2^33
有点混乱,自己认真整理一下就好了