在計(jì)算機(jī)中,圖形是一門很高深的學(xué)問,在我看來,因?yàn)槔锩嫔婕暗奖容^多的數(shù)學(xué)問題...... 用JAVA是可以畫圖的。 今天介紹簡單的用Java畫直線。 Java提供在組件上繪圖的功能,通過繪圖類Graphics對象調(diào)用繪圖方向?qū)崿F(xiàn)。 1、Graphics圖形類 Graphics類在Java.awt中被定義,可以設(shè)置圖形顏色、字符串字體等,其聲明如下: public abstract class Graphics extends Object { public abstract Color getColor(); //獲取當(dāng)前顏色 public abstract void setColor(Color c); //設(shè)置顏色 public abstract void drawLine(int x1, int y1, int x2, int y2); //畫直線 public void drawRect(int x, int y, int width, int height) ; //畫矩形 public abstract void fillRect(int x, int y, int width, int height); //填充矩形 public abstract void drawOval(int x, int y, int width, int height); //畫橢圓 public abstract void drawString(String str, int x, int y); //顯示字符串 public abstract Font getFont(); /獲得顏色 public abstract void setFont(Font font);//設(shè)置顏色 } 但Graphics類是一個(gè)抽象類,不能被具體地實(shí)例化,要具體的畫圖,一般是通過在畫布上進(jìn)行畫。 2、畫布類Canvas Canvas類也在Java.awt中。 可通過創(chuàng)建Canvas的實(shí)例來創(chuàng)建畫布類組件。 3、組件繪圖方法 在Java.awt.Component類中聲明有方法: public void paint(Graphics g); //組件繪制圖形 public void repaint(); //調(diào)用paint()方法刷新圖形 4、示例 在窗口中畫對角線。 其完整代碼如下: import java.awt.*; import javax.swing.*; class CircleCanvas extends Canvas{//本類繼承自畫布類,用作繪圖的面板,因?yàn)?/span>Java不允許多繼承,所以要用此類 public void paint(Graphics g){//調(diào)用方法paint()來繪圖 int x=this.getWidth()/2;//定義坐標(biāo)x為橫坐標(biāo)的中心,this.getWidth()是取當(dāng)前窗口的寬度 int y=this.getHeight()/2;//定義坐標(biāo)y為縱坐標(biāo)的中心,this.getHeight()是取當(dāng)前窗口的高度 g.setColor(Color.red);//設(shè)置顏色為紅色 g.drawLine(x, y, this.getWidth(), this.getHeight());//本例我是從中心開始畫四條直線,最終合成對角線,調(diào)用Graphics的erawLine()方法來畫直線 g.setColor(Color.green); g.drawLine(x, y, 0, 0); g.setColor(Color.red); g.drawLine(x, y, this.getWidth(), 0); g.setColor(Color.green); g.drawLine(x, y, 0, this.getHeight()); } } public class Draw_Circle extends JFrame{//主類 private CircleCanvas circle;//創(chuàng)建對象 public Draw_Circle(){ super("畫直線"); this.setVisible(true); this.setBounds(200, 200, 200, 200); circle=new CircleCanvas();//創(chuàng)建實(shí)例 this.getContentPane().add(circle); } publicstaticvoid main(String args[]){ new Draw_Circle(); } } 其運(yùn)行結(jié)果如下: 從本例可以發(fā)現(xiàn),用Canvas繪圖時(shí),創(chuàng)建實(shí)例時(shí)并沒有去調(diào)用paint()方法,此方法是在創(chuàng)建類時(shí)自動調(diào)用的。 |
|