java 绘图技术

  • 绘图原理

    • Component 类提供了两个和绘图相关最重要的方法:
    1. paint(Graphics g) 绘制组件的外观
    2. repaint()刷新组件的外观。
    • 当组件第一次在屏幕显示的时候,程序会自动的调用 paint()方法来绘制组件。

    • 以下情况 paint()将会被调用:

    1. 窗口最小化,再最大化
    2. 窗口的大小发生变化
    3. repaint 函数被调用
  • Graphics 类

    1. 画直线 drawLine(int x1,int y1,int x2,int y2)

    2. 画矩形边框 drawRect(int x, int y, int width, int height)

    3. 画椭圆边框 drawOval(int x, int y, int width, int height)

    4. 填充矩形 fillRect(int x, int y, int width, int height)

    5. 填充椭圆 fillOval(int x, int y, int width, int height)

    6. 画图片 drawlmage(lmage img, int x, int y, …)

    7. 画字符串 drawString(String str, int x, int y)

    8. 设置画笔的字体 setFont(Font font)

    9. 设置画笔的颜色 setColor(Color c)


      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      package com.hspedu.draw;
      import javax.swing.*;
      import java.awt.*;
      public class DrawCircle extends JFrame{ //对应窗口

      // 定义一个面板
      private MyPanel mp = null;
      public static void main(String[] args) {
      new DrawCircle();
      System.out.println("退出程序");

      }
      public DrawCircle() {
      // 初始化面板
      mp = new MyPanel();
      // 把面板放入窗口
      this.add(mp);
      // 设置窗口大小
      this.setSize(400,300);
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.setVisible(true);//可以显示



      }

      }
      //1、先定义一个MyPanel,集成JPanel类,,画图形.
      class MyPanel extends JPanel{

      @Override
      public void paint(Graphics g) {
      super.paint(g); //调用父类的方法完成初始化.
      //画一个圆形
      // g.drawOval(100,100,100,100);
      // g.drawLine(10,10,100,0);
      // g.drawRect(10,10,100,100);
      // g.setColor(Color.blue);
      // g.fillRect(10,10,100,100);
      // g.setColor(Color.red);
      // g.fillOval(10,10,100,100);
      // 画图片
      // 1、获取图片资源
      // Image image = Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bg.jpg"));
      // g.drawImage(image,10,10,300,221,this);
      g.setColor(Color.red);
      g.setFont(new Font("幼圆",Font.BOLD,50));
      g.drawString("野兽先辈",200,200);
      }
      }