import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
public class elastic {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame f = new DrawFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.show();
}
}
class DrawFrame extends JFrame
{
public DrawFrame()
{
setTitle( "画图程序 ");
setSize(WIDTH,HEIGHT);
Container contentPane = getContentPane();
DrawPanel p = new DrawPanel();
contentPane.add(p);
contentPane.add(p.statusPanel,BorderLayout.SOUTH);
}
public static final int WIDTH = 600;
public static final int HEIGHT = 600;
}
class DrawPanel extends JPanel implements MouseListener,MouseMotionListener
{
public DrawPanel()
{
lines = new ArrayList();
colors = new ArrayList();
setBackground(Color.WHITE);
this.addMouseMotionListener(this);
this.addMouseListener(this);
statusPanel= new JPanel();
//statusPanel.setSize(40, 200);
//statusPanel.setBackground(Color.RED);
statusPanel.setLayout(new BorderLayout());
statusLabel = new JLabel( " " );
statusPanel.add(statusLabel,BorderLayout.CENTER);
}
public void setDrawColor()
{
setForeground(focucolor);
}
public void mouseDragged(MouseEvent e)
{
x2 = e.getX();
y2 = e.getY();
statusLabel.setText( " 横坐标为: "+x2+ "纵坐标为: "+y2);
repaint();
}
public void mouseMoved(MouseEvent e)
{
}
/下面五个方法是实现MouseListener的接口的方法
public void mousePressed(MouseEvent e)
{
x1 = e.getX();
y1 = e.getY();
x2 = -1;
repaint();
}
public void mouseReleased(MouseEvent e)
{
colors.add(getForeground());
lines.add(new Line2D.Double(x1, y1, e.getX(), e.getY()));
x2 = -1;
statusLabel.setText( " ");
repaint();
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(this.getForeground());
int count = lines.size();
for(int i = 0;i <count;i++)
{
Line2D.Double line = (Line2D.Double)lines.get(i);
g2.setColor((Color)colors.get(i));
g2.draw(line);
}
if (x2 != -1)
g2.drawLine(x1, y1, x2, y2);
}
//用来清除图像
public void clearCanvas()
{
lines.clear();
colors.clear();
x2 = -1;
repaint();
}
private ArrayList lines;
private ArrayList colors;
private int x1,y1,x2,y2;
private Color focucolor;
private JLabel statusLabel;
JPanel statusPanel;
}