用GeneralPath和Graphics2D的draw方法画圆柱体
下面是示例程序源码:
import java.awt.geom.*;
import java.awt.*;
import javax.swing.*;/**
*使用GeneralPath画圆柱的示例程序
*@author Eastsun
*@version 1.0 2006/12/20
*/public class DrawColumn extends JPanel{
/**
*得到一个表示圆柱的GeneralPath
*@param x 圆柱的左上角的x坐标
*@param y 圆柱的左上角的y坐标
*@param height 圆柱的高
*@param radius 圆柱的半径
*@param arch 圆柱底圆的弧高
*/
public static GeneralPath getColumn(int x,int y,int height,int radius,int arch){
GeneralPath path =new GeneralPath(new Ellipse2D.Float(x,y-arch,2*radius,2*arch));
path.lineTo(x+2*radius,y+height);
path.append(new Arc2D.Float(x,y+height-arch,2*radius,2*arch,0,-180,Arc2D.OPEN),false);
path.lineTo(x,y);
return path;
}
private int x,y,height,radius,arch;
public DrawColumn(){
x =40;
y =80;
height =120;
radius =40;
arch =20;
}
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.red);
g2.draw(getColumn(x,y,height,radius,arch));
}
public static void main(String[] args){
JFrame frame =new JFrame(\"DrawColumn\");
JPanel panel =new DrawColumn();
panel.setPreferredSize(new Dimension(320,240));
frame.add(panel); //注意,用JDK1.5或以上版本编译,否则需改为frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}