怎样在Java中实现绘图时的橡皮线效果?
怎样在Java中实现绘图时的橡皮线效果?
恰好以前给别人写过一个示例:
import java.awt.geom.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
/**
*简单的画图程序
*@author [url=http://eastsun.javaeye.com]Eastsun[/url]
*@version .1
*/
public class DrawPanel extends JFrame{
LinkedList<Shape> shapeList =new LinkedList<Shape>();
Shape shape;
Stroke stroke =new BasicStroke(1.0f,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND,
0,new float[]{8f,3f},1);
Point start,end;
final String[] type =new String[]{\"Line\",\"Rectangle\",\"Ellipse\"};
JComboBox comboBox =new JComboBox(type);
public DrawPanel(){
super(\"DrawPanel\");
JPanel panel =new JPanel(){
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 =(Graphics2D)g;
g2.setColor(Color.white);
g2.fillRect(0,0,getWidth(),getHeight());
g2.setColor(Color.black);
for(Shape s:shapeList) g2.draw(s);
if(shape!=null){
g2.setStroke(stroke);
g2.setPaint(Color.blue);
g2.draw(shape);
}
}
};
panel.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
start =e.getPoint();
}
public void mouseReleased(MouseEvent e){
if(shape!=null) shapeList.add(shape);
shape =null;
repaint();
}
});
panel.addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
end =e.getPoint();
Object select =comboBox.getSelectedItem();
if(select.equals(type[0])) shape =new Line2D.Float(start,end);
else{
if(select.equals(type[1])) shape =new Rectangle();
else shape =new Ellipse2D.Float();
((RectangularShape)shape).setFrameFromDiagonal(start,end);
}
repaint();
}
});
panel.setPreferredSize(new Dimension(320,240));
add(panel,BorderLayout.NORTH);
add(comboBox,BorderLayout.SOUTH);
pack();
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
new DrawPanel();
}
}
[此贴子已经被作者于2007-3-1 21:53:23编辑过]