使用 Graphics 类

介绍

所述 Graphics 类可以绘制到 Java 组件,诸如 Jpanel ,它可以被用于绘制字符串,线条,形状和图像。这是通过重写了的 paintComponent(Graphics g) 方法 JComponent 你在使用绘图 Graphics 收到的参数对象做图形:

class Board

import java.awt.*;
import javax.swing.*;

public class Board extends JPanel{
    
    public Board() {
        setBackground(Color.WHITE);
    }

    @override
    public Dimension getPreferredSize() {
        return new Dimension(400, 400);
    }
    
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        // draws a line diagonally across the screen
        g.drawLine(0, 0, 400, 400);
        // draws a rectangle around "hello there!"
        g.drawRect(140, 180, 115, 25);
    }        
}

包装类 DrawingCanvas

import javax.swing.*;

public class DrawingCanvas extends JFrame {
    
    public DrawingCanvas() {
        
        Board board = new Board();
        
        add(board); // adds the Board to our JFrame    
        pack(); // sets JFrame dimension to contain subcomponents
        
        setResizable(false);
        setTitle("Graphics Test");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        setLocationRelativeTo(null); // centers window on screen
    }
    
    public static void main(String[] args) {
        DrawingCanvas canvas = new DrawingCanvas();
        canvas.setVisible(true);
    }
}

颜色

要绘制具有不同颜色的形状,你必须在每次绘制调用之前使用 setColor 设置 Graphics 对象的颜色 :

g.setColor(Color.BLUE);  // draws a blue square
g.fillRect(10, 110, 100, 100);

g.setColor(Color.RED);  // draws a red circle
g.fillOval(10, 10, 100, 100);

g.setColor(Color.GREEN);  // draws a green triangle
int[] xPoints = {0, 200, 100};
int[] yPoints = {100, 100, 280};
g.fillPolygon(xPoints, yPoints, 3);