使用Java语言画线、圆、椭圆(计算机图形学)

利用Java语言实现画图(线、圆、椭圆)

package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;

public class ToolBarListener extends MouseAdapter implements       ActionListener,MouseMotionListener
{
private JPanel paintPanel=null;
private static int paintFlag=-1;
private double x1,y1,x2,y2;
private double newX1,newY1,newX2,newY2;
private Shape shape;

public ToolBarListener(JPanel panel)
{
    this.paintPanel=panel;
}

public void actionPerformed(ActionEvent e)
{
    if(e.getActionCommand().equals("直线"))
    {
        paintFlag=1;
    }
    else if(e.getActionCommand().equals("椭圆"))
    {
        paintFlag=2;
    }
    else if(e.getActionCommand().equals("矩形"))
    {
        paintFlag=3;
    }        
}

public void mousePressed(MouseEvent e)
{
    x1=e.getX();
    y1=e.getY();        
}

public void mouseDragged(MouseEvent e)
{
    x2=e.getX();
    y2=e.getY();
    
    if(paintFlag==1)
    {
        shape=new Line2D.Double(x1,y1,x2,y2);            
    }
    else if(paintFlag==2)
    {
        coordinateChange();
        shape=new Ellipse2D.Double(newX1,newY1,newX2-newX1,newY2-newY1);            
    }
    else if(paintFlag==3)
    {
        coordinateChange();
        shape=new Rectangle2D.Double(newX1,newY1,newX2-newX1,newY2-newY1);            
    }
    
    ((PaintPanel)paintPanel).setShape(shape);
    ((PaintPanel)paintPanel).repaint();
}

public void mouseMoved(MouseEvent e) 
{
    
}

public void mouseReleased(MouseEvent e)
{
    ((PaintPanel)paintPanel).addShape(shape);
    ((PaintPanel)paintPanel).repaint();
}

private void coordinateChange()
{
    if((x1y2))
    {            
        newX1=x1;newY1=y2;
        newX2=x2;newY2=y1;
    }
    else if((x1>x2) && (y1>y2))
    {
        newX1=x2;newY1=y2;
        newX2=x1;newY2=y1;
    }
    else if((x1>x2) && (y1

你可能感兴趣的:(Java)